Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

MenuBar and Toolbar problem  RSS feed

 
eLL Pascual
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Rob Spoor
Sheriff
Posts: 20895
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!