//Create a New Java Project called CheckBoxes.
//Write a program with two checkboxes, one labeled BLUE and the other labeled ORANGE. When no checkbox is selected, the panel’s background color should be gray and its foreground color should be black.
//When only the BLUE checkbox is selected, the panel’s background color should be blue and its foreground color should be yellow. When only the ORANGE checkbox is selected, the panel’s background color should be orange and its foreground color should be white.
//When both checkboxes are selected, the panel’s background color should be blue and its foreground color should be orange. Please note that checkboxes require the use of the ItemListener, as opposed to the ActionListener
This is your main and driver class:
package com.colourchanger;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ColorDemo extends JFrame implements ItemListener{
int r=0,g=0,b=0;
JCheckBox orange,green,blue;
JPanel P = new JPanel();
JPanel cpanel = new JPanel();
Container pane = getContentPane();
ColorDemo(String cd){
super(cd);
orange = new JCheckBox("orange");
orange.addItemListener(this);
/* green = new JCheckBox("green");
green.addItemListener(this);*/
blue = new JCheckBox("blue");
blue.setSelected(true);
blue.addItemListener(this);
cpanel.add(orange);
//cpanel.add(green);
cpanel.add(blue);
getContentPane().add(cpanel,"North");
setSize(400,400);
setVisible(true);
getContentPane().add(P);
P.setAlignmentX(JComponent.CENTER_ALIGNMENT);
setVisible(true);
}
public static void main(String[] args)
{
ColorDemo cd = new ColorDemo("Color Check Box");
cd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie){
if(ie.getItem() == orange)
if(orange.isSelected()) r=255; else r=0;
//if(ie.getItem() == green)
//if(green.isSelected()) g=255; else g=0;
if(ie.getItem() == blue)
if(blue.isSelected()) b=255; else b=0;
P.setBackground(new Color(r,g,b));
}
}
Get Answers For Free
Most questions answered within 1 hours.