Forums Register Login

MenuBar and Toolbar problem

+Pie Number of slices to send: Send
In my program, I created a menu bar and a toolbar, meaning, aside from the menu bar I have buttons as a (standard)toolbar also. But the problem is when I click the menu items, the program is calling the message box that is supposedly a message box that should appear when I click a button from the toolbar, and when I click a button from the toolbar, it is throwing

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

Why is it happening?

Actually this my code in actionPerformed:

code:
----------------------------------------------------------------------------

public void actionPerformed(ActionEvent ae){

JMenuItem source = (JMenuItem)(ae.getSource());

String cmd = ae.getActionCommand(); //for toolbar buttons
String description = null; //for toolbar button's JOptionPane


if(source.getText().equalsIgnoreCase("open") || OPEN.equals(cmd)){

description = "OPEN";

try{
FileInputStream fi=new FileInputStream(openfile());
BufferedReader br=new BufferedReader(new InputStreamReader(fi));
String s01=br.readLine();
if(s01 != null) textArea.setText(s01);
br.close();
fi.close();
}
catch(Exception ex){}
}
else if(source.getText().equalsIgnoreCase("save as")){
try{
FileOutputStream fo=new FileOutputStream(writefile());
PrintStream ps=new PrintStream(fo);
ps.println(textArea.getText());
ps.close();
fo.close();
}
catch(Exception ex){}
}


displayResult("The user clicked " + description);
}

----------------------------------------------------------------------------

If it is confusing and you need to see my other codes, please tell me.

Thanks!
+Pie Number of slices to send: Send
Obviously "JMenuItem source = (JMenuItem)(ae.getSource());" is the culprit - the source is not a JMenuItem but a JButton.

Fortunately for you, JMenuItem and JButton have a common ancestor class - AbstractButton. Use that as the source class and you'll be OK.
What's that smell? I think this tiny ad may have stepped in something.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1387 times.
Similar Threads
About Opening a file
About Saving in a file
Some confusing ones part2
Why isn't my code Opening a Saved file?
Implementing function in new dialog
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 02:53:02.