0

早上好,我尝试为 JComboBox 和 JButton 添加相同的动作侦听器,但在运行时ClassCastException发生如下java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JButton,已将侦听器添加到它们,如下所示:

jComboBox1.addActionListener(this);
jButton1.addActionListener(this);

actionPerformed 方法是:

public void actionPerformed(ActionEvent e){

    JButton button=(JButton)e.getSource();
    JComboBox sCombo=(JComboBox)e.getSource();

    if(sCombo.equals(jComboBox1))
        listModel.addElement(sCombo.getSelectedItem());
    else
        listModel2.addElement(sCombo.getSelectedItem());

    if(button.equals(jButton1))
        System.out.println("Button1 is pressed");
}
4

2 回答 2

3

假设您实际上正在实现一个ActionListener,您可以在这里使用instanceof

Object sourceObject = e.getSource();
if (sourceObject instanceof JButton) {
   JButton button=(JButton)sourceObject;
   ...
} else if (sourceObject instanceof JComboBox) {
   JComboBox comboBox = (JComboBox)sourceObject;
   ...
}

但更好的做法是为每个控件分配一个单独的侦听器,尤其是在考虑到每个控件正在执行的非常不同的任务的情况下。

于 2013-01-01T01:41:33.293 回答
2

这是合法的,但这样做

public void actionPerformed(ActionEvent e) {
    if(e.getSource() instanceof JButton) {
        JButton button=(JButton)e.getSource();
        System.out.println("Button1 is pressed");
    } else if(e.getSource() instanceof JComboBox) {
        /* watever you doing with combobox */
    }
}
于 2013-01-01T01:42:04.797 回答