hi,
I get above exception for the following code.

public void actionPerformed(ActionEvent e) 
  {
    try
    {
    
    JComboBox Oone =(JComboBox)e.getSource();
    
    String item = (String) Oone.getSelectedItem();
    //lbl.setText(item);
    System.out.println("selected item is:"+item);
    
    String command = e.getActionCommand();
    if(command.equals("Cancel"))
    {
    	System.exit(0);
    }
    
    if(command.equals("Next"))
    {
//    		frame.remove(tab);
			check chk = new check(item);
			//frame.setContentPane(tst1);

			frame.setLocation(250,150);
	        frame.setSize(500,200);
	        frame.setVisible(true);
    }
    
    }catch(Exception e1)
    {
    	System.out.println(e1);
    }
    
  }

will you please tell me what is wrong here.
Thanks in advance.

Recommended Answers

All 3 Replies

JComboBox Oone =(JComboBox)e.getSource();

The above is the statement that is most probably throwing the exception, most probably you have added this same ActionListener to another UI component such as a button or a textfield etc (which could not / cannot be cast into an object of type JComboBox) and hence the JVM threw the ClassCastException when that object generated some ActionEvent.
Also next time please paste the complete exception stack trace as it helps us identify which is the exact line on which the exception was thrown rather that us having to scan through the code figuring out from which lines the Exception could have originated.

Thanks.I get this exception

java.lang.ClassCastException : javax.swing.JButton cannot be cast to javax.swing.JComboBox

I want to get the value of combobox and when click on next button that value will pass to check class object.

what can I do to overcome this problem.

Simple at the start of actionPerformed() itself put an "if" statement like this :-

public void actionPerformed(ActionEvent e) {
  if(e.getSource() instanceOf JComboBox)  {
    // Code to execute for Combobox
  } else  if (e.getSource() instanceOf JButton){
    // Code to execute if Button clicked.
  }
}

Or else if your comboBox and button objects were declared at the class level itself, you can check directly which component generated the event as in :-

Class XFrame extends JFrame implements ActionListener {
  JComboBox abc;
  JButton btn;
  public XFrame() {
    super("Test Frame");
    abc = new JComboBox........
    btn = new JButton.....
  }

  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == abc) {
      // code to execute when combobox abc generates event.
    } else if (e.getSource() == btn){
      // code to execute when button btn generates the event
    }
    else ....
    // event handling for other components
  }
}

** Note the code is just for illustration.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.