Java Swing How to - Fill enum to JComboBox








Question

We would like to know how to fill enum to JComboBox.

Answer

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/*from w w w . j av  a2 s  .c  o  m*/
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JPanel {

  String SIGNAL = "Signal";
  private List<JComboBox<ComboColor>> comboList = new ArrayList<>();

  public Main() {
    setLayout(new GridLayout(0, 1));

      DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(
          ComboColor.values());
      JComboBox<ComboColor> combo = new JComboBox<>(cModel);
      add(createComboLabelPanel(1, combo));
      comboList.add(combo);

  }

  private JPanel createComboLabelPanel(int index, JComboBox<ComboColor> combo) {
    JPanel panel = new JPanel();
    JLabel label = new JLabel(SIGNAL + " " + index);
    label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    label.setOpaque(true);
    combo.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent evt) {
        ComboColor cColor = (ComboColor) combo.getSelectedItem();
        label.setBackground(cColor.getColor());
      }
    });

    panel.add(label);
    panel.add(combo);
    return panel;
  }

  public static void main(String[] args) {
    Main mainPanel = new Main();

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(mainPanel);
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);

  }
}

enum ComboColor {
  RED("Red", Color.RED), GREEN("Green", Color.GREEN);

  private String text;
  private Color color;

  public String getText() {
    return text;
  }

  public Color getColor() {
    return color;
  }

  private ComboColor(String text, Color color) {
    this.text = text;
    this.color = color;
  }

  @Override
  public String toString() {
    return text;
  }
}