Hi, I wrote a simple Java program that allows changing the background color of itself by clicking on the radio button, like this:

import java.awt.*;
import java.awt.event.*;

class Colors extends Frame implements ItemListener, ActionListener{
 Label lblTxt = new Label("Choose a color:");
 Label lblInform = new Label();
 CheckboxGroup cbg = new CheckboxGroup();
 Checkbox cbRed = new Checkbox("Red", cbg, false);
 Checkbox cbGreen = new Checkbox("Green", cbg, false);
 Checkbox cbBlue = new Checkbox("Blue", cbg, false);
 Button btnExit = new Button("Exit");
 Panel pn = new Panel();
 Colors(String title){
  super(title);
  add(pn);
  pn.setLayout(new GridLayout(5, 1));
  pn.add(lblTxt);
  pn.add(cbRed);
  pn.add(cbGreen);
  pn.add(cbBlue);
  pn.add(lblInform);
  add(btnExit, BorderLayout.PAGE_END);
  btnExit.addActionListener(this);
  cbRed.addItemListener(this);
  cbGreen.addItemListener(this);
  cbBlue.addItemListener(this);  
 } 
 public void actionPerformed(ActionEvent ae){
  System.exit(0);
 }
 public void itemStateChanged(ItemEvent e){
   	
   if(cbRed.getState() == true){     
     lblInform.setText("You've chosen red color!");
     this.setBackground(Color.red);      
   }
   if(cbGreen.getState() == true){ 
     lblInform.setText("You've chosen green color!");
     this.setBackground(Color.green);
   } 
   if(cbBlue.getState() == true){
     lblInform.setText("You've chosen blue color!");
     this.setBackground(Color.green);
   } 
 }    
}


class ChooseColors{
 public static void main(String args[]){
   Colors objColor = new Colors("List of colors");
   objColor.setBackground(Color.yellow);
   objColor.setSize(300, 500);
   objColor.show();
 }

}

The program runs almost Ok but the problem is that the setBackground() methods that get called in the itemStateChanged() method doesn't run. So, the background color of the application doesn't change. The strange thing is that when I tried other methods with the object 'this' inside the itemStateChanged() method, they all ran well. Can anyone tell me what the problem is?

little test of program
1. replace your line

pn.setLayout(new GridLayout(5, 1));

with pn.setLayout(new GridLayout(6, 0)); 2. replace your part of program

if(cbBlue.getState() == true){
lblInform.setText("You've chosen blue color!");
this.setBackground(Color.green);
}

with

if (cbBlue.getState() == true) {
            lblInform.setText("You've chosen blue color!");
            Component[] componentArray = pn.getComponents();
            int componentCount = componentArray.length;
            System.out.println("componentCount= " + componentCount);
            for (int i = 0; i < componentCount; i++) {
                System.out.println(componentArray[i].toString());
            }
            pn.setBackground(Color.blue);
        }

Interpret result and go ahead

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