Hi all, I cant get my brain around the logic of making a check box add a specific color when it is checked. Also, when the other boxes are check, it will add that color to the selected color as well. here is my code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class ColorViewerFrame extends JFrame
   public ColorViewerFrame()
      colorPanel = new JPanel();
      add(colorPanel, BorderLayout.CENTER);

   public void createControlPanel()
      class ColorListener implements ChangeListener
         public void stateChanged(ChangeEvent event)

      ChangeListener listener = new ColorListener();

      redCheckBox = new JCheckBox("Red");

      greenCheckBox = new JCheckBox("Green");

      blueCheckBox = new JCheckBox("Blue");
      JPanel controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());


      add(controlPanel, BorderLayout.SOUTH);      
      Reads the check box values and sets the panel to
      the selected color.
   public void setSampleColor()
      // Read CheckBox values
    	  colorPanel.setBackground(255, 0, 0);
      if(redCheckBox.isSelected() ++ greenCheckBox.isSelected())
    	  colorPanel.setBackground(255, 225, 0);
      if(redCheckBox.isSelected() ++ blueCheckBox.isSelected())
    	  colorPanel.setBackground(255, 0, 255);
    	  colorPanel.setBackground(0, 255, 0);
    	  colorPanel.setBackground(0, 0, 255);

      // Set panel background to selected color
      //colorPanel.setBackground(0, 0, 0);
   private JPanel colorPanel;
   private JCheckBox redCheckBox;
   private JCheckBox greenCheckBox;
   private JCheckBox blueCheckBox;
import javax.swing.JFrame;

// new class
public class ColorViewer
   public static void main(String[] args)
      ColorViewerFrame frame = new ColorViewerFrame();

any help would be super!

Edited 7 Years Ago by Himerz: n/a

well two things come to mind, you have a listener and i think that means you need to have your class implement it. i.e.

public class MyClass implements ActionListener {

you can also use your extend as well. if i remember right extend is inheritance and implement is an interface it's using.

once you do this i guess you can use the action event method, which is called when an ation happens to the thing you implemented, i.e checking.

public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {

this is a code example above from: http://java.sun.com/docs/books/tutorial/uiswing/components/button.html.

i think "disable" would be the title next to the checkbox. so you change that to "blue" and they check blue and your blue variable goes to 1, it happens again it goes to 0.


This article has been dead for over six months. Start a new discussion instead.