代码如下:
package extends1;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame implements ItemListener{
private ButtonGroup bg=new ButtonGroup();
private JRadioButton rbColorr=new JRadioButton("red");
private JRadioButton rbColorg=new JRadioButton("green");
private JRadioButton rbColorb=new JRadioButton("blue");
private JPanel jpl=new JPanel();
public Main()
{
bg.add(rbColorr);
bg.add(rbColorg);
bg.add(rbColorb);
jpl.add(rbColorr);
jpl.add(rbColorg);
jpl.add(rbColorb);
rbColorr.addItemListener(this);
rbColorg.addItemListener(this);
rbColorb.addItemListener(this);
this.add(jpl);
this.setSize(300,300);
this.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
Object color=e.getItemSelectable();
if(color==rbColorr)
this.getContentPane().setBackground(Color.red);
else if(color==rbColorg)
this.getContentPane().setBackground(Color.green);
else
this.getContentPane().setBackground(Color.blue);;
}
public static void main(String[] args)throws Exception
{
new Main();
}
}