2.2 Develop an program that contains three check boxes and 30 x 30 pixel canvas.The three checkboxes should be labeled “Red”, “Green”,”Blue”. The selection of the check boxes determine the color of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple.
ChangeCanvasColor.java
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ChangeCanvasColor extends JFrame implements ItemListener{JCheckBox jCbRed, jCbBlue, jCbGreen;Canvas c=new Canvas();ChangeCanvasColor(){setLayout(new FlowLayout());c.setSize(100,100);add(c);jCbRed=new JCheckBox("Red");jCbGreen=new JCheckBox("Green");jCbBlue=new JCheckBox("Blue");jCbRed.addItemListener(this);jCbGreen.addItemListener(this);jCbBlue.addItemListener(this);add(jCbRed);add(jCbGreen);add(jCbBlue);setSize(600,350);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}int r=0,g=0,b=0;public void itemStateChanged(ItemEvent ie){if(jCbRed.isSelected()){r=255;canvasColor();}else if(!jCbRed.isSelected()){r=0;canvasColor();}///////////////////////////////////////////////////////////////////////////////if(jCbGreen.isSelected()){g=255;canvasColor();}else if(!jCbGreen.isSelected()){g=0;canvasColor();}//////////////////////////////////////////////////////////////////////////////if(jCbBlue.isSelected()){b=255;canvasColor();}else if(!jCbBlue.isSelected()){b=0;canvasColor();}}public void canvasColor(){c.setBackground(new Color(r,g,b));}public static void main(String arg[]){new ChangeCanvasColor();}}
Happy Coding :)
0 Comments
Post a Comment