📄 testradiobuttondemo.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestRadioButtonDemo extends JFrame implements ItemListener
{
private JRadioButton jrbRed,jrbYellow,jrbGreen;
private Light light;
private ButtonGroup bg=new ButtonGroup();
/**
* @param args
*/
public TestRadioButtonDemo()
{
this.setTitle("模拟交通灯");
JPanel p1=new JPanel();
p1.setSize(200,200);
light=new Light();
light.setSize(40,90);
p1.add(light);
JPanel p2=new JPanel();
p2.add(jrbRed=new JRadioButton("Red"));
p2.add(jrbYellow=new JRadioButton("Yellow"));
p2.add(jrbGreen=new JRadioButton("Green"));
bg.add(jrbRed);
bg.add(jrbYellow);
bg.add(jrbGreen);
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
jrbRed.addItemListener(this);
jrbYellow.addItemListener(this);
jrbGreen.addItemListener(this);
}
public static void main(String[] args)
{
TestRadioButtonDemo frame=new TestRadioButtonDemo();
frame.setSize(250,180);
frame.setVisible(true);
}
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,yellow,green;
public Light()
{
this.red=false;
this.yellow=false;
this.green=false;
}
public void turnOnRed()
{
this.red=true;
this.yellow=false;
this.green=false;
this.repaint();
}
public void turnOnGreen()
{
this.red=false;
this.yellow=false;
this.green=true;
this.repaint();
}
public void turnOnYellow()
{
this.red=false;
this.yellow=true;
this.green=false;
this.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.fillOval(10, 35, 20, 20);
g.fillOval(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.fillOval(10, 10, 20, 20);
g.fillOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else if(green)
{
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.fillOval(10, 10, 20, 20);
g.fillOval(10, 35, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else
{
g.setColor(Color.black);
g.fillOval(10, 10, 20, 20);
g.fillOval(10, 35, 20, 20);
g.fillOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
}
public Dimension getPreferredSize()
{
return new Dimension(40,90);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -