-2

Inside my actionPerformed method I have the two following lines of code,

JButton pressed =(JButton)e.getSource();
JMenuItem pressedSave = (JMenuItem)e.getSource();

Why is this not allowed? I get the following compiler error

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JMenuItem

I need to be able to get the text for both a JButton and a JMenuItem. How can I do this?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
ugCode
  • 29
  • 3

3 Answers3

2

The error is very clear. You are trying to assign a Jbutton to a JMenuItem.

You are getting the error on line 2, which means that line 1 is flawless, which also implies that e.getSource() is a JButton, not a JMenuItem.

What you can do is use the instanceof operator to determine which component triggered the event:

Object comp = e.getSource();

if(comp instanceof JButton) {
    // A JButton triggered the event
    JButton pressed =(JButton) comp;

    // Do something with your 'pressed' button
}
else if(comp instanceof JMenuItem) {
    // A JMenuItem triggered the event
    JMenuItem pressedSave = (JMenuItem) comp;

    // Do something with your 'pressedSave' menu item
}
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • I do not understand though, how am i trying to assign a jbutton to jmenuitem? its a brand new object. How would I fix this? – ugCode Jan 01 '16 at 20:31
  • @ugCode in what way is it a brand new object, it is the source of the event. – luk2302 Jan 01 '16 at 20:32
1

You are not getting a compiler error.

It is "allowed", it just does not work.

If it was not allowed, then the compiler would complain.

But what you have got here is a RuntimeException because you have a JButton which simply cannot be cast to a JMenuItem. They are unrelated types - how should a conversion / cast between those two look like?

What you can do is cast both types JButton and JMenuItem to their common supertype AbstractButton.

luk2302
  • 55,258
  • 23
  • 97
  • 137
1

JMenuItem is not a subclass of JButton, however you can cast both to AbstractButton. That may work depending on what you want to do

Gacci
  • 1,388
  • 1
  • 11
  • 23