当ComboBoxModel变为空时

当ComboBoxModel变为空时

本文介绍了当ComboBoxModel变为空时,清除最后选择的值JCombobox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个场景:

我有两个JComboBox (分别称为combo1和combo2),它们从数据库中获取其值 [在数据库中,这两个具有1:M的关系].当屏幕出现时,我使用数据库中的值填充combo1,然后获取列表中的第一项并获取其相应的值以填充combo2.

I have two JComboBoxes (call them combo1 and combo2 ) that get their values from a database[In the DB, these two have a 1:M relationship]. When the screen shows up I populate combo1 with values from the database and then take the first entry in the list and get its corresponding values to populate combo2.

由于combo2的值取决于combo1中选择的内容,因此,每次combo1中的选择更改时,都会调用数据库以获取匹配值以填充combo2.

Since the values of combo2 depend on what is selected in combo1, every time the selection changes in combo1 a call is made to the database to get matching values to populate combo2.

现在这是一个问题:

说我在combo1中有两个条目,第二个条目没有对应的combo2值.当我选择combo1的第二个条目时,combo2上的最后一个选定值不会清除. [记住combo2的模型是空的,因此应该没有选择任何内容]

Say I have two entries in combo1 and the second entry has no corresponding values for combo2. When I select the second entry of combo1, the last selected value on combo2 does not clear. [Remember the model for combo2 is empty and therefore there shouldn't anything selected]

问题:如果模型为空,如何清除combo2中的文本?

这是示例代码:

public void select(final Entry entry) {
      if (entry == null)
         return;

         int index = entryList.indexOf(entry); // instance of SelectionInList from JGoodies
         boolean positive = index >= 0 && index <= entryList.getSize() - 1;

         if (positive) {

              entryList.setSelection(entry);


               subEntryList.setList(entryList.loadSubEntries(entry.getID()));
               if (!subEntryList.isEmpty()) {
                    SubEntry e = subEntryList.getElementAt(0);
                    select(e);
                 }
        }

}

推荐答案

如果组合框模型为空,则视图应自动清除.如果您导出自己的模型,请不要忘记删除条目来调用DefaultComboBoxModel.fireIntervalRemoved().

If you have an empty combobox model the view should clear automatically. If you derived an own model do not forget to call DefaultComboBoxModel.fireIntervalRemoved() if you remove entries.

另一种方法(在这种情况下不建议使用)是使用combobox.setSelectedItem(null);.

Another (in this case not recommended) way is to use combobox.setSelectedItem(null);.

这篇关于当ComboBoxModel变为空时,清除最后选择的值JCombobox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:27