简体   繁体   English

ItemStateChanged被两次调用到JComboBox中

[英]ItemStateChanged called twice into JComboBox

Hello and i am using one Combobox and when i triggered IteamStateChage event then that action called twice. 您好,我正在使用一个组合框,当我触发IteamStateChage事件时,该操作被调用了两次。 but if i called twice i can not make make it possible what i want to do. 但是,如果我打了两次电话,我将无法实现自己想做的事情。

So is there any way to called IteamStatechange evet only once. 因此,有什么方法只能将IteamStatechange evet调用一次。 when i change iteam into the Jcombobox. 当我将iteam更改为Jcombobox时。 i just need once action of itemStatechange. 我只需要一次itemStatechange的操作。 and using Item State change only.![Here Screen Shot for same.][1] 并且仅使用项目状态更改。![此处为相同的屏幕截图。] [1]

please help me for same. 请同样帮我。 and thank you for you ans in advance. 并提前感谢您。

In this context, this is expected behaviour. 在这种情况下,这是预期的行为。 The combobox is signaling the deselection of the current item and the selection of the new item. 组合框表示当前项目已取消选择,新项目已选择。

In the itemStateChanged method, you need to inspect the state of the ItemEvent to determine what you should do. itemStateChanged方法中,您需要检查ItemEvent的状态以确定应该执行的操作。

public void itemStateChanged(ItemEvent evt) {

    switch (evt.getStateChanged()) {
        case ItemEvent.DESELECTED:
            // Do what ever you want when the item is deselected
            break;
        case ItemEvent.SELECTED:
            // Do what ever you want when the item is selected
            break;
    }
}

Here is an example how to determin if the change event is Select or Deselect: 这是一个如何确定更改事件是“选择”还是“取消选择”的示例:

JComboBox<String> comboBox = new JComboBox<>(new String[] {"one", "two", "foo"});
 comboBox.addItemListener(new ItemListener() {
     @Override
     public void itemStateChanged(ItemEvent e) {
         System.out.println("Change");
         if(e.getStateChange() == ItemEvent.SELECTED){
             System.out.println("Selected");
         }
         if(e.getStateChange() == ItemEvent.DESELECTED){
             System.out.println("Deselected");
         } 
     }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM