Davide Melis
Davide Melis

Reputation: 39

How can I populate a choice box with an array of objects in Java?

I have a choice box in my GUI

Choice choice = new Choice();
choice.setBounds(75, 11, 93, 20);
panel.add(choice);

I also have this array of objects:

public Planet[] planetList;

every

Planet

has a name field. I'd like to populate the choice box with my planetList and display the name field, so when the users choice the planet by name, it selects the Object Planet that has that name.

If it's easier, I could use a combobox or whatever I could use as a dropdown list of my array.

Upvotes: 0

Views: 1077

Answers (1)

Jay Smith
Jay Smith

Reputation: 2490

To create java.awt.Choice:

Choice fruitChoice = new Choice();

To fill in the choices:

  fruitChoice.add("Apple");
  fruitChoice.add("Grapes");
  fruitChoice.add("Mango");
  fruitChoice.add("Peer");

To get the selected item:

String fruit = fruitChoice.getItem(fruitChoice.getSelectedIndex());

Upvotes: 0

Related Questions