【问题标题】:Java combo box model and get selected itemJava组合框模型并获取选定项
【发布时间】:2012-06-06 20:08:52
【问题描述】:

下面的代码显示了我在使用组合操作时遇到的问题。 getSelectedItem() 被多次触发,而不仅仅是在选择时触发。只需加载框架调用该方法 3 次。每次单击组合框都是一次调用,即使它只是用于下拉菜单而不是实际选择。在可编辑文本区域内单击也会触发 getSelectedItem() 方法。有没有办法过滤这个事件?或者在盒子模型级别验证数据的替代方法?

public class SSCCE {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    JFrame aframe = new JFrame();
    Combo _combo = new Combo();
    _combo.addElement("This");
    _combo.addElement("That");
    JComboBox _box = new JComboBox(new Combo());
    _box.setEditable(true);
    aframe.add(_box);
    aframe.setVisible(true);

}

static class Combo extends DefaultComboBoxModel{
    public Combo(){
    }
    int i = 0;
    @Override
    public Object getSelectedItem() {
        System.out.println("Get selected Item" + i);
        i++;
        return super.getSelectedItem();
    }
  }
}

【问题讨论】:

  • 你想要完成什么?可能有比覆盖 getSelectedItem() 更好的选择。
  • 它在哪里说每个选择事件只会被调用一次?这是动作监听器的工作,而不是模型覆盖。

标签: java swing events awt


【解决方案1】:

请参阅this tutorial 了解如何使用 JComboBox,特别是有关处理事件的部分。您应该将ActionListener 添加到您的组合框中。当用户实际做出表明他们的选择已确认的手势时,它将被触发。

【讨论】:

    【解决方案2】:

    您已查看 ItemListenerActionListener 添加到 JComboBox

    【讨论】:

      【解决方案3】:

      getSelectedItem() 确实会触发多次,以及动作事件。对于可编辑的组合框,该操作会为 comboboxchanged 触发一次,而为 comboboxedited 触发一次。我在 getSelectedItem 中设置了不特定于最终项目的验证,并将其余部分移到组合框更改的过滤操作事件中。我完全忽略了 comboboxedited 事件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-15
        • 2011-08-28
        • 1970-01-01
        • 2016-08-19
        • 2013-10-27
        相关资源
        最近更新 更多