I have to create a GUI that when I click on the buttons it changes the color of the background. Below is what I have but I can't figure out what code to put in and where to change 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.JButton;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ColorViewer extends JFrame
{
public ColorViewer()
{
colorPanel = new JPanel();
add(colorPanel, BorderLayout.CENTER);
createControlPanel();
setSampleColor();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createControlPanel()
{
class ColorListener implements ChangeListener
{
public void stateChanged(ChangeEvent event)
{
setSampleColor();
}
}
ChangeListener listener = new ColorListener();
redButton = new JButton("Red");
redButton.addChangeListener(listener);
greenButton = new JButton("Green");
greenButton.addChangeListener(listener);
blueButton = new JButton("Blue");
blueButton.addChangeListener(listener);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(3, 2));
controlPanel.add(new JLabel("Red"));
controlPanel.add(redButton);
controlPanel.add(new JLabel("Green"));
controlPanel.add(greenButton);
controlPanel.add(new JLabel("Blue"));
controlPanel.add(blueButton);
add(controlPanel, BorderLayout.SOUTH);
}
/**
Reads the slider values and sets the panel to
the selected color.
*/
public void setSampleColor()
{
// Set panel background to selected color
colorPanel.repaint();
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if(o == redButton){/*set color to red*/}
else if(o == greenButton){/*set color to green*/}
else if(o == blueButton){/*set color to blue*/}
}
private JPanel colorPanel;
private JButton redButton;
private JButton greenButton;
private JButton blueButton;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
}
import javax.swing.JFrame;
public class ColorViewerMain
{
public static void main(String[] args)
{
ColorViewer frame = new ColorViewer();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}