在comboBox java中添加和选择项目时都获得相同的ActionEvent

时间:2019-01-17 23:24:58

标签: java user-interface combobox actionlistener

我的Jcombobox具有ActionListener,当从comboBox中选择一项时,它需要在表中添加新行, 不幸的是,我还可以选择将新项目插入相同的comboBox。

我的问题是,两个动作都具有相同的动作事件“ comboBoxChanged”

此处是一些代码:

cmbAllMovies.addActionListener(new ActionListener() {
			
	@Override
	public void actionPerformed(ActionEvent e) {
			
		Movie movie = (Movie) cmbAllMovies.getSelectedItem();
		Object [] rowData= {movie.getName(),movie.getYear(),movie.getlanguage()}; 
		tblModel.addRow(rowData);
	}
});

谢谢,

1 个答案:

答案 0 :(得分:0)

免责声明:您的问题尚不清楚,因此答案基于我个人的猜测,即您不希望在向组合框添加新元素时触发组合框的动作侦听器。

解决方案是在添加新元素时删除组合框的动作侦听器,然后还原/重新添加动作侦听器。

SSCCE

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test extends JFrame implements ActionListener {

    private JComboBox<String> comboBox;

    public Test() {
        super("test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout());
        String[] movies = { "Rambo 1", "Rocky 1", "Fargo", };
        comboBox = new JComboBox<>(movies);
        comboBox.addActionListener(this);
        JTextField textField = new JTextField(10);
        JButton button = new JButton("Add movie");
        button.addActionListener(e -> {
            String selectedMovie = textField.getText();
            comboBox.removeActionListener(this);// Remove the action listener
            comboBox.addItem(selectedMovie); // Add the movie without any action listener
            comboBox.addActionListener(this); // Restore action listener
        });
        add(comboBox);
        add(textField);
        add(button);
        setSize(300, 300);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new Test().setVisible(true);
        });
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(comboBox.getSelectedItem() + " is a great movie.");
    }

}