为了简短起见,我想设计一个Java小程序,该小程序显示带有三个相邻按钮的交通信号灯。一种表示红色,一种表示琥珀色,一种表示绿色。
我的问题是:我不知道如何将每个按钮与右椭圆形链接。所有的椭圆都属于相同的Graphics变量g。如果我更改颜色,则所有三个都将更改。
据我所知,有一个名为canvas的超类可以帮助将其自身实体中的每个对象分开,但是我知道有一种更简单的方法。
我怎样才能做到这一点?
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.Applet;
public class Traffic extends Applet
implements ActionListener
{
int colourNum; //global variable which is responible for changing the light
Button bttn1 = new Button ("Stop Traffic");
Button bttn2 = new Button ("Caution");
Button bttn3 = new Button ("Proceed");
public void init ()
{
setBackground (Color.lightGray);
bttn1.addActionListener (this); // stop light
bttn2.addActionListener (this); // yellow light
bttn3.addActionListener (this); // green light
add (bttn1);
add (bttn2);
add (bttn3);
}
public void paint (Graphics g) // responsible for graphics "within" the window
{
g.setColor (Color.black);
switch (colourNum)
{
case 1:
g.setColor (Color.red);
break;
}
g.fillOval (30, 40, 20, 20); // red light
g.fillOval (30, 70, 20, 20); // yello light
g.fillOval (30, 100, 20, 20); // green light
}
public void actionPerformed (ActionEvent evt)
{
if (evt.getSource () == bttn1)
colourNum = 1;
else if (evt.getSource () == bttn2)
colourNum = 2;
else
colourNum = 3;
repaint ();
}
}
最佳答案
public void paint (Graphics g) // responsible for graphics "within" the window
{
g.setColor (Color.black);
g.setColor(colourNum == 1? Color.red : Color.red.darker().darker());
g.fillOval (30, 40, 20, 20); // red light
g.setColor(colourNum == 2? Color.yellow : Color.yellow.darker().darker());
g.fillOval (30, 70, 20, 20); // yello light
g.setColor(colourNum == 3? Color.green : Color.green.darker().darker());
g.fillOval (30, 100, 20, 20); // green light
}