java JComboBox 动作监听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6539001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:16:27  来源:igfitidea点击:

JComboBox Action listener

javaswingjcomboboxactionlistener

提问by user650608

I'm having this problem. I have multiple JComboBoxes (5 total).

我有这个问题。我有多个 JComboBoxes(总共 5 个)。

To each comboBox I add an ActionListener, but the same ActionListener for all of them, called:

对于每个组合框,我添加了一个 ActionListener,但为所有组合框添加了相同的 ActionListener,称为:

ComboBoxActionPerformed(java.awt.event.ActionEvent e)

and when that action is performed I look at the event (e) and do:

当执行该操作时,我会查看事件 (e) 并执行以下操作:

JComboBox c = ((JComboBox)e.getSource());
//DO WORK relating to c as thats the combobox that triggered.

but the problem is when I change something in any of my comboboxes the Action is always triggered by the last combo box to which I am attaching the actionlistner.

但问题是当我更改任何组合框中的某些内容时,Action 总是由我附加 actionlistner 的最后一个组合框触发。

anyone have any idea?

任何人有任何想法?

I then switched to ItemListner. This is what im doing a

然后我切换到 ItemListner。这就是我在做的

class MyActionListner implements ItemListener 
{
    //STUFF
        @Override
        public void itemStateChanged(ItemEvent evt) 
        {
            //DO STUFF
    }
}

public JComboBox createCombo()
{
    JComboBox box = new JComboBox();
        box.setModel(new javax.swing.DefaultComboBoxModel(new String[] 
                { "val1", "val2","val3" }));
        RulesActionListner actionL = new RulesActionListner();
        box.addItemListener(actionL);
return box;
}

and createCombo gets called multiple times but regardless of which combo box item was changed in side my ItemStateChanged method its comming from the last combo box that was created

并且 createCombo 被多次调用,但无论在我的 ItemStateChanged 方法中更改了哪个组合框项目,它都来自创建的最后一个组合框

createCombo is called at runtime, so i have a variable number of comboboxes.

createCombo 在运行时被调用,所以我有可变数量的组合框。

回答by jzd

Add separate action listeners instead of having one action listener run through if statements for each call. That section of the code will have logic that most likely has a bug that is causing the last combo box to be selected. (Maybe an elsestatement that should be else if, etc.).

添加单独的动作侦听器,而不是让一个动作侦听器为每个调用运行 if 语句。该部分代码的逻辑很可能存在导致选择最后一个组合框的错误。(也许else应该是一个声明else if,等等)。

Separating it out will be more OO and will be more flexible long term.

将其分离将更加面向对象,并且从长远来看会更加灵活。

回答by mKorbel

@user650608 your questions isn't clear for me, do you mean - going this way, or am I wrong ?,

@user650608 你的问题对我来说不清楚,你的意思是 - 走这条路,还是我错了?,

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {

    private static final long serialVersionUID = 1L;
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

    public ComboBoxTwo() {
        String[] items = {"Select Item", "Color", "Shape", "Fruit", "Size"};
        mainComboBox = new JComboBox(items);
        mainComboBox.addActionListener(this);
        mainComboBox.addItemListener(this);
        //prevent action events from being fired when the up/down arrow keys are used
        //mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add(mainComboBox, BorderLayout.WEST);
        subComboBox = new JComboBox();//  Create sub combo box with multiple models
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        subComboBox.addItemListener(this);
        getContentPane().add(subComboBox, BorderLayout.CENTER);
        String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
        subItems.put(items[1], subItems1);
        String[] subItems2 = {"Select Shape", "Circle", "Square", "Triangle"};
        subItems.put(items[2], subItems2);
        String[] subItems3 = {"Select Fruit", "Apple", "Orange", "Banana"};
        subItems.put(items[3], subItems3);
        String[] subItems4 = {"Select Size", "Big", "Middle", "Small"};
        subItems.put(items[4], subItems4);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String item = (String) mainComboBox.getSelectedItem();
        Object o = subItems.get(item);
        if (o == null) {
            subComboBox.setModel(new DefaultComboBoxModel());
        } else {
            subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == mainComboBox) {
                if (mainComboBox.getSelectedIndex() != 0) {
                    FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
                            mainComboBox.getSelectedItem().toString(), "Please wait,  Searching for ..... ");
                }
            } 
        }
    }

    private class FirstDialog extends JDialog {

        private static final long serialVersionUID = 1L;

        FirstDialog(final Frame parent, String winTitle, String msgString) {
            super(parent, winTitle);
            setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
            JLabel myLabel = new JLabel(msgString);
            JButton bNext = new JButton("Stop Processes");
            add(myLabel, BorderLayout.CENTER);
            add(bNext, BorderLayout.SOUTH);
            bNext.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    setVisible(false);
                }
            });
            javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }
            });
            t.setRepeats(false);
            t.start();
            setLocationRelativeTo(parent);
            setSize(new Dimension(400, 100));
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

回答by Snicolas

Did you try using an ItemListener instead ?

您是否尝试使用 ItemListener 代替?

The docsays an ActionEvent is fired every time the combo box is edited.

该文档说每次编辑组合框时都会触发 ActionEvent。

Regards, Stéphane

问候, 斯蒂芬