Search code examples
javaswingobjectselectionjcombobox

How do I detect the selected object in a JComboBox?


I have made a JComboBox and populated it with the result of toString of an object type which I created myself.

I want to be able to call upon the selected object from the JComboBox and then use a method from its class. However, even though my JComboBox only contains one object type (The one I made), Java doesn't know this and therefore I can;t use something like...

MyObject selectedObject = MyComboBox.getSelectedItem();

as Java cannot accept that only a "MyObject" will ever be selected.

How am I supposed to get the user to select an object of my own?


Solution

  • I think you need cast it, like

    MyObject selectedObject = (MyObject) MyComboBox.getSelectedItem();