早安,我试图为JComboBox和JButton添加相同的动作侦听器,但在运行时ClassCastException
发生如下java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to javax.swing.JButton
,已将侦听器添加到它们中,如下所示: / p>
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");
}
答案 0 :(得分:3)
假设您实际上正在实施ActionListener
,可以在此使用instanceof
:
Object sourceObject = e.getSource();
if (sourceObject instanceof JButton) {
JButton button=(JButton)sourceObject;
...
} else if (sourceObject instanceof JComboBox) {
JComboBox comboBox = (JComboBox)sourceObject;
...
}
但更好的做法是为每个控件分配一个单独的监听器,特别是在这里给出了每个控件执行的非常不同的任务。
答案 1 :(得分: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 */
}
}