|
Can't seem to get this program to work. Here are the instructions:
This program displays an interface with five option buttons in a Frame. When clicked, each button changes the background color of the Frame to Blue, Red, Yellow, Pink, or Gray.
1. Write the code for the class header. Name the file ColorButtons. Save the program as a Java source code file.
2. Construct an instance of a CheckboxGroup with five Checkboxes.
3. Write the constructor method for ColorButtons(). In that method, assign FlowLayout as the layout manager. Use the add() method to add each of the Checkboxes to the Frame. Write the code for the addWindowListener() method.
4. Write the code for the actionPerformed() method, which uses the getState() method to test which Checkbox the user clicked. Use nested if statements.
|
|
|
import java.awt.*;
import java.awt.event.*;
public class ColorButtons extends Frame implements ItemListener
{
Checkbox blue, red, yellow, pink, gray;
public ColorButtons()
{
CheckboxGroup group = new CheckboxGroup();
blue = new Checkbox("blue", false, group);
red = new Checkbox("red", false, group);
yellow = new Checkbox("yellow", false, group);
pink = new Checkbox("pink", false, group);
gray = new Checkbox("gray", false, group);
blue.addItemListener(this);
red.addItemListener(this);
yellow.addItemListener(this);
pink.addItemListener(this);
gray.addItemListener(this);
// Checkbox does not accept an ActionListener
// as the compiler reports when you try to compile
// this class with the next 4 lines un-commented
//blue.addActionListener(new ActionListener()
//{
// public void actionPerformed(ActionEvent e) {}
//});
addWindowListener(new Closer());
setLayout(new FlowLayout());
add(blue);
add(red);
add(yellow);
add(pink);
add(gray);
setSize(300,175);
setLocation(200,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
Checkbox checkbox = (Checkbox)e.getSource();
Color color = null;
if(blue.getState())
color = Color.blue;
else if(red.getState())
color = Color.red;
else if(yellow.getState())
color = Color.yellow;
else if(pink.getState())
color = Color.pink;
else if(gray.getState())
color = Color.gray;
else
{
System.out.println("unexpected checkbox sending events: " +
checkbox.getLabel());
color = color.black;
}
setBackground(color);
}
}
private class Closer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
new ColorButtons();
}
}
|
|
|
|
|
|
|
|
|
|