Problem getting selected item as string from JComboBox
Hey there I'm trying to implement my own custom JComboBox class as here:
Code :
package guitesting;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
public class ComboBoxPotSelection extends JComboBox implements ActionListener{
private String selection;
public ComboBoxPotSelection(String[] pots){
this.addItem(pots);
this.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent CmbBoxEvent){
JComboBox combo = (JComboBox)CmbBoxEvent.getSource();
selection = (String)combo.getSelectedItem();
}
});
this.setEditable(false);
this.setSelectedIndex(0);
this.setVisible(true);
}
public String retStrVal(){
return selection;
}
}
But when i try to run the implementation Im getting:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
at guitesting.ComboBoxPotSelection$1.actionPerformed( ComboBoxPotSelection.java:17)
I cant understand why I cant cast my selected item to a string??
Re: Problem getting selected item as string from JComboBox
The item you're adding is a String array, so that's what you get back.
Read the API for JComboBox and follow the link to the Swing tutorial on How to Use Combo Boxes, where you will find a number of code samples.
db