实在找不到哪儿错了.大家帮帮忙了.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RadioButtonDemo extends JFrame implements ItemListener {
private JRadioButton jrbRed,jrbYellow,jrbGreen;
private ButtonGroup btg=new ButtonGroup();
private Light light;
public static void main(String args[]){
RadioButtonDemo frame = new RadioButtonDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack();
frame.setSize(250,170);
frame.setVisible(true);
}
public RadioButtonDemo(){
this.setTitle("RadioButton demo");
JPanel p1 = new JPanel();
p1.setSize(200,200);
p1.setLayout(new FlowLayout(FlowLayout.CENTER));
light=new Light();
light.setSize(40,90);
p1.add(light);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jrbRed=new JRadioButton("Red",false));
p2.add(jrbYellow=new JRadioButton("Yellow",false));
p2.add(jrbGreen=new JRadioButton("Green",false));
jrbRed.setMnemonic('R');
jrbYellow.setMnemonic('Y');
jrbGreen.setMnemonic('G');
btg.add(jrbRed);
btg.add(jrbYellow);
btg.add(jrbGreen);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(p1,BorderLayout.CENTER);
this.getContentPane().add(p2,BorderLayout.SOUTH);
jrbRed.addItemListener(this);
jrbYellow.addItemListener(this);
jrbGreen.addItemListener(this);
}
public void itemStateChanged(ItemEvent e){
if(jrbRed.isSelected()) light.turnonRed();
if(jrbYellow.isSelected()) light.turnonYellow();
if(jrbGreen.isSelected()) light.turnonGreen();
}
}
class Light extends JPanel{
private boolean red;
private boolean yellow;
private boolean green;
public Light(){
turnonGreen();
}
public void turnonRed(){
red=true;
yellow=false;
green=false;
repaint();
}
public void turnonYellow(){
red=false;
yellow=true;
green=false;
repaint();
}
public void turnonGreen(){
red=false;
yellow=false;
green=true;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(red){
g.setColor(Color.red);
g.fillOval(10, 10, 20, 20);
g.setColor(Color.black);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else if(yellow){
g.setColor(Color.yellow);
g.fillOval(10, 35, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10,20,20);
g.drawOval(10, 60, 20, 20);
}
else if(green){
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
}
else {
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
}
}
public Dimension getpreferredSize(){
return new Dimension(40,90);
}
}