题目大意:做一个简单的交通灯,要求框架里有三个单选按钮(red,green,yellow),一组交通指示灯(三个灯泡)。选择单选按钮后,相应的灯会亮,一次只能亮一种灯。
以下是我的程序,执行以后面板上有按钮,可就是没有图像,求各位指点啊
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLight extends JFrame
{
PaintPanel paintPanel=new PaintPanel();//申请画图面板,按钮面板和三个单选按钮
JPanel buttons=new JPanel();
JRadioButton red=new JRadioButton("red");
JRadioButton green=new JRadioButton("green");
JRadioButton yellow=new JRadioButton("yellow");
TrafficLight()
{
ButtonGroup ni=new ButtonGroup();//将单选按钮加入按钮组
ni.add(red);
ni.add(green);
ni.add(yellow);
buttons.setLayout(new FlowLayout());//将单选按钮加入按钮面板
buttons.add(red);
buttons.add(green);
buttons.add(yellow);
setLayout(new BorderLayout());//将按钮面板和画图面板加入框架
add(paintPanel,BorderLayout.NORTH);
add(buttons,BorderLayout.SOUTH );
red.addActionListener(new ActionListener(){//为三个单选按钮设置监听
public void actionPerformed(ActionEvent e){repaint();}});
yellow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){repaint();}});
green.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){repaint();}});
}
public class PaintPanel extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawRect(getWidth()/2-10,20, 20, 60);//按要求绘制交通灯
if(!red.isSelected())
g.drawOval(getWidth()/2,30,15,15);//亮红灯
else
g.fillOval(getWidth()/2,30,15,15);//熄灭红灯
if(!green.isSelected())
g.drawOval(getWidth()/2,50,15,15);//亮绿灯
else
g.fillOval(getWidth()/2,50,15,15);//熄灭绿灯
if(!yellow.isSelected())
g.drawOval(getWidth()/2,70,15,15);//亮黄灯
else
g.fillOval(getWidth()/2,70,15,15);//熄灭黄灯
}
}
public static void main(String [] args)//主函数
{
TrafficLight mine=new TrafficLight();
mine.setTitle("TrafficLight");
mine.setSize(800,500);
mine.setVisible(true);
}
}