Write a program with three checkboxes and a circle drawn in black. Each checkbox
ID: 3699930 • Letter: W
Question
Write a program with three checkboxes and a circle drawn in black. Each checkbox represents a color (red, blue, or green) and should be labeled accordingly. When only the RED checkbox is selected, color the circle RED. When only the BLUE checkbox is selected, color the circle BLUE. When only the GREEN checkbox is selected, color the circle GREEN. When both the RED and BLUE checkboxes are selected, color the circle purple. When both the BLUE and GREEN checkboxes are selected, color the circle cyan. If no checkbox is selected or any other checkbox combinations are selected, the circle should remain black.
Please note that checkboxes require the use of the ItemListener, as opposed to the ActionListener.
Explanation / Answer
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Chkbox extends Applet implements ItemListener
{
Checkbox ch1,ch2,ch3;
public void init()
{
//setBackground(Color.blue);
ch1= new Checkbox("Yes");
ch2= new Checkbox("No");
ch3= new Checkbox("Yes");
add(ch1);
add(ch2);
add(ch3);
ch1.setBackground(Color.red);
ch2.setBackground(Color.BLUE);
ch3.setBackground(Color.GREEN);
//g.drawOval(20,20,200,120);
//g.setColor(Color.DARK_GRAY);
//g.fillOval(20, 10, 100, 100);
ch1.addItemListener(this);
ch2.addItemListener(this);
ch3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
if(ch1.getState())
{
g.setColor(Color.RED);
g.fillOval(20, 10, 100, 100);
}
if(ch2.getState())
{
g.setColor(Color.BLUE);
g.fillOval(20, 10, 100, 100);
}
if(ch3.getState())
{
g.setColor(Color.GREEN);
g.fillOval(20, 10, 100, 100);
}
if(ch2.getState() && ch1.getState())
{
g.setColor(Color.magenta);
g.fillOval(20, 10, 100, 100);
}
if(ch2.getState() && ch3.getState())
{
g.setColor(Color.cyan);
g.fillOval(20, 10, 100, 100);
}
if(!ch2.getState() && (!ch1.getState()) && !ch3.getState())
{
g.setColor(Color.BLACK);
g.fillOval(20, 10, 100, 100);
}
}}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.