Troy Squillaci
Troy Squillaci

Reputation: 27

Populating Generic JComboBox with Enum

I have a JPanel with multiple JComboBoxes for user input. Each JComboBox is instantiated with the values of an enum. There are several of these JComboBoxes, so I want to have a method to instantiate and set up each one. For example:

private JComboBox card_type_box = this.createCombo(CardType.values());

...   

private JComboBox createCombo(CardType[] card_types)
{
  final JComboBox combo = new JComboBox(card_types);
  combo.setSelectedIndex(0);
  combo.addActionListener(this);
  ...
  return combo;
}

The issue with this method is that it only accepts enums of type CardType. Is it possible to have this method accept an arbitrary enum to create a new JComboBox?

Upvotes: 0

Views: 209

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

Try using something like (under Java 7)...

private <E extends Enum> JComboBox<E> createCombo(E[] values) {
    final JComboBox<E> combo = new JComboBox(values);

or

private <E extends Enum> JComboBox createCombo(E[] values) {
    final JComboBox combo = new JComboBox(values);

Under Java 6, for example...

Upvotes: 1

Related Questions