I am trying to use a combo box to change the background color. I have the following code but it is not working correctly. The combo box is there with the three choices but the choices are not changing the color of the background.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ColorViewerComboBox extends JFrame
{
private JLabel sampleField;
private JComboBox colornameCombo;
private ActionListener listener;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
public ColorViewerComboBox()
{
sampleField = new JLabel();
add(sampleField, BorderLayout.CENTER);
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setSampleColor();
}
}
ActionListener listener = new ColorListener();
createControlPanel();
setSampleColor();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createControlPanel()
{
JPanel colornamePanel = createComboBox();
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(3,1));
controlPanel.add(colornamePanel);
add(controlPanel, BorderLayout.SOUTH);
}
public JPanel createComboBox()
{
colornameCombo = new JComboBox();
colornameCombo.addItem("Red");
colornameCombo.addItem("Green");
colornameCombo.addItem("Blue");
colornameCombo.setEditable(true);
colornameCombo.addActionListener(listener);
JPanel panel = new JPanel();
panel.add(colornameCombo);
return panel;
}
public void setSampleColor()
{
String colorname = (String) colornameCombo.getSelectedItem();
sampleField.setColor(new Color(colorname));
sampleField.repaint();
}
}