Java Swing How to - Use JComboBox to change color








Question

We would like to know how to use JComboBox to change color.

Answer

import java.awt.Color;
import java.awt.Dimension;
/*  ww w  .java 2 s  .com*/
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  Hue hue = Hue.values()[0];
  public Main() {
    setPreferredSize(new Dimension(320, 240));
    setBackground(hue.getColor());
    JComboBox colorBox = new JComboBox();
    for (Hue h : Hue.values()) {
      colorBox.addItem(h);
    }
    colorBox.addActionListener(e -> {
        Hue h = (Hue) colorBox.getSelectedItem();
        Main.this.setBackground(h.getColor());
    });
    this.add(colorBox);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

enum Hue {

  Cyan(Color.cyan), Magenta(Color.magenta), Yellow(Color.yellow), Red(Color.red), Green(
      Color.green), Blue(Color.blue);

  private final Color color;

  private Hue(Color color) {
    this.color = color;
  }
  public Color getColor() {
    return color;
  }
}