• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class Cast Exception  RSS feed

 
Lucky Singh
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can someone tell me why that line is giving me an exception when I run my program?

public void actionPerformed(ActionEvent e)
{
String command = (String) ((JButton)e.getSource()).getText();
if(command.equals ("submit"))
{
nameE = nameInput.getText();
locChoices = (JComboBox)(e.getSource());****CLASS CAST EXCEPTION***
locationE = (String)(locChoices.getSelectedItem());
empAgent.processFormInfo(nameE, locationE);
}
else
{
System.out.println("The reset button was pressed");
}
} //end method actionPerformed.
 
Torgil Zethson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first line of your actionPerformed method you successfully cast the source of the ActionEvent to a JButton. On the line where you get the ClassCastException you try to cast the same source to a JComboBox. The source of the ActionEvent can't be both a JButton and a JComboBox, so you will have to get to the JComboBox some other way. Maybe by keeping a reference to it in a member variable?
 
Lucky Singh
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot. I was able to solve the problem. However, I cannot understand why when I add actionListener(this) to a textbox and button, it works fine but for a JComboBox and button it gives me a class cast exception.
 
Torgil Zethson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get a ClassCastException because your implementation of actionPerformed is faulty. You can certainly use the same ActionListener for both a JButton and a JComboBox, but you must be careful when you implement it:




Alternatively, if you don't want to keep member variables pointing to your button and combobox:

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!