【问题标题】:JComboBox WorkingJComboBox 工作
【发布时间】:2012-08-30 07:23:01
【问题描述】:

我有一个组合框,其中包含一个项目,可以说“a”。我想仅在手动选择项目“a”时调用该组合框的动作侦听器。 我也尝试过 ItemStateChanged,但它的工作原理类似于 Action Listener。

我该怎么做?

【问题讨论】:

  • 添加监听器之前设置初始选择可能出现需要这样做。如果这不是问题,发布您的sscce 可能有助于澄清。

标签: java swing jcombobox actionlistener itemlistener


【解决方案1】:

看看下面的例子。

// Create an editable combobox
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);

// Create and register listener
 MyItemListener actionListener = new MyItemListener();
 cb.addItemListener(actionListener);

class MyItemListener implements ItemListener {
 // This method is called only if a new item has been selected.
  public void itemStateChanged(ItemEvent evt) {
    JComboBox cb = (JComboBox)evt.getSource();

    // Get the affected item
    Object item = evt.getItem();

    if (evt.getStateChange() == ItemEvent.SELECTED) {
        // Item was just selected
    } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
        // Item is no longer selected
    }
}
}

【讨论】:

    【解决方案2】:

    我认为你不能只监听一个 ComboBox Item 的事件,但是当监听整个组合框时,在回调中你可以在处理事件之前检查选定的项目(或忽略它)。

    Sumit Singh提供的例子中,检查受影响的项目

    // Get the affected item
    Object item = evt.getItem();
    
    //check item
    if(item == <the item you want to watch>)
    {
        //process
    }
    

    【讨论】:

      【解决方案3】:

      创建 2 个 actionlistener 怎么样,一个会查看是否选择了 'a',如果是,它将调用第二个

      【讨论】:

      • 能否请您发布有关如何实现的正确解释和代码,因为它似乎与我无关......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2016-11-13
      • 2014-07-27
      • 2011-04-27
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      相关资源
      最近更新 更多