I have been playing about with a GUI today and trying add different elements to it,
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
//Do Something
}
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
if(petName == "Cat")
{
//Do Something
}
}
When i click jButton1 it does what i want it to do and when i select “Cat” from the combobox it does what i want it to do, but only when i click jButton1 and not when i select cat it gives me the following error
javax.swing.JButton cannot be cast to javax.swing.JComboBox
Any ideas obviously something to do with the comboxbox code and when i remove the code from JCombobox down the error doesnt appear.
Any help would be good, not homework just be messing about and seeing if i can learn new things
First of all, don’t compare strings using
==, use theequalsmethod. That is, changeto
(
==compares references, not the objects the references refer to)Related question:
Regarding the “JButton cannot be cast to JComboBox”-issue, it seems to me like you’re simply forgetting an
elsethere. Try the following:(or simply
returnfrom the method once you’re done with theDo somethingrelated to the JButton.)