0

简而言之,我想设计一个显示带有三个相邻按钮的红绿灯的 Java 小程序。一个说红灯,一个说黄灯,一个说绿灯。


我的问题是:我不知道如何将每个按钮与正确的椭圆链接起来。所有的椭圆都属于同一个图形变量 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 ();
    }
}
4

1 回答 1

2
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
}
于 2013-02-22T19:28:22.000 回答