1

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

aioobe
  • 413,195
  • 112
  • 811
  • 826
user445714
  • 383
  • 1
  • 9
  • 24

1 Answers1

5

First of all, don't compare strings using ==, use the equals method. That is, change

petName == "Cat"

to

petName.equals("Cat")

(== 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 else there. Try the following:

if (e.getSource() == jButton1) {
    //Do Something
} else {

    JComboBox cb = (JComboBox)e.getSource();
    String petName = (String)cb.getSelectedItem();

    if(petName == "Cat") {
        //Do Something
    }
}

(or simply return from the method once you're done with the Do something related to the JButton.)

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Thanks for the advice regards == and .equals, should have spotted that one, as for the else its still giving me the error when i add this. – user445714 Aug 23 '11 at 20:11
  • The error is due to the fact that `e.getSource()` returns a `JButton`. In other words, the error occurs when the source of the event is a `JButton` and you insist on trying to cast it to a `JComboBox`. Have a look at your program logic and try to figure out the origin of the event, and make sure you don't try to cast it to a `JComboBox` if it may come from a `JButton`. – aioobe Aug 23 '11 at 20:14
  • Would this issue be around this jButton1.addActionListener(this); petList.addActionListener(this); in the constructor – user445714 Aug 23 '11 at 20:52
  • Could be. Try wrapping the combo-box specific stuff in `if (e.getSource() == theComboBox) { ... }` to make sure you're not trying to cast the `e.getSource()` into an `JComboBox` without knowing you should. – aioobe Aug 23 '11 at 20:57