ronak07
ronak07

Reputation: 43

AWT Radio Button

I want to change the background of the frame based on the selected radio button. This has to be done using AWT. The current code just change the color to Blue. When clicked on Green, nothing is changed.

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

class A extends Frame implements ItemListener
{
    Checkbox c1,c2;
    CheckboxGroup cbg;
    A()
    {
        setLayout(new FlowLayout());
        cbg= new CheckboxGroup();
        c1= new Checkbox("Blue",cbg,false);
        c2= new Checkbox("Green",cbg,true);
        this.add(c1);
        this.add(c2);
        c1.addItemListener(this);
        c2.addItemListener(this);
    }  

    public void itemStateChanged(ItemEvent e)
    {
        if(e.getStateChange()==ItemEvent.SELECTED)
            this.setBackground(Color.BLUE);
        else if(e.getStateChange()==ItemEvent.SELECTED)
            this.setBackground(Color.Green);
        else
            this.setBackground(Color.BLACK);
    }  

    public static void main(String[] args)
    {
        A a= new A();
        a.setSize(500,500);
        a.setTitle("ME");
        a.setVisible(true);
        a.addWindowListener(new WindowAdapter() {  
            public void windowClosing(WindowEvent we){System.exit(0);}  
        });
    }
}

Upvotes: 1

Views: 1045

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

The underlying problem (besides th compilation error) is that the condition for the if and the else if are identical. It might be better to check the source of the event and compare it to either c1 or c2.

Note that if there should be a 'black' option, there will need to be a third check box.

Upvotes: 1

Related Questions