Why use a switch at all? Rather, just let enum hold the color information (encapsulate it) and thereby do all the dirty work. The advantage of this is that if you change your enum, you do not need to root through all the code that uses it, changing all the switch statements. For instance:
import java.awt.Color; public enum MyColor { RED("Red", Color.red), BLUE("Blue", Color.blue), YELLOW("Yellow", Color.yellow); private String text; private Color color; private MyColor(String text,Color color) { this.text = text; this.color = color; } public String getText() { return text; } public Color getColor() { return color; } @Override public String toString() { return text; } }
and an example of how this can be used is as follows:
import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") class MyColorTest extends JPanel { private static final Dimension PREF_SIZE = new Dimension(400, 300); public MyColorTest() { for (final MyColor myColor : MyColor.values()) { add(new JButton(new AbstractAction(myColor.getText()) { @Override public void actionPerformed(ActionEvent arg0) { MyColorTest.this.setBackground(myColor.getColor()); } })); } } @Override public Dimension getPreferredSize() { return PREF_SIZE; } private static void createAndShowUI() { JFrame frame = new JFrame("MyColorTest"); frame.getContentPane().add(new MyColorTest()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } }
source share