早上好,我尝试为 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");
}