【问题标题】:Swing JComboBox get previous item when new item selectedSwing JComboBox在选择新项目时获取上一个项目
【发布时间】:2020-05-18 02:11:12
【问题描述】:

我是挥杆初学者 我有以下代码:

String[] names = new String[]{
            "James", "Joshua", "Matt", "John", "Paul" };

    JComboBox comboBox = new JComboBox<String>(names);
    // Create an ActionListener for the JComboBox component.
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox = (JComboBox) event.getSource();

            // Print the selected items and the action command.
            Object selected = comboBox.getSelectedItem();
            System.out.println("Selected Item  = " + selected);

        }
    });

假设选择的对象是 Paul,我在 John 之后选择。所以这里 actionPerfomed 被触发,comboBox.getSelectedItem(); 将返回我们John。我的问题是之前有什么方法可以拦截Paul 吗?

【问题讨论】:

  • 好吧,你可以使用ItemListener,它会根据记忆告诉你“from”和“to”事件,或者你可以只保留对最后选择的值的引用:/
  • 我该如何实现它?
  • 嗯,你可以从How to Write an Item Listener 开始,我认为How to Use Combo Boxes 有一些例子

标签: java swing jcombobox


【解决方案1】:

使用addItemListener 检查是否已选择任何项目

comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    String selected = (String) event.getItem();
                    // add your logic
                }
            }
        });

资源:JComboBoxComponent

【讨论】:

  • 请注意,这可能会被调用两次,一次用于取消选择,一次用于选择 - 因此您可能需要在决定应该做什么之前检查类型...和因为这是 OP 提出的基本问题,您可以考虑演示它;)
  • 我认为 OP 想要上一个被选中的项目,所以你应该使用 ItemEvent.DESELECTED 否则你可以像例子中那样使用 ActionLIsener 因为它会给你当前的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多