Java Applets-在不使用'canvas'的情况下创建交互式交通信号灯?

时间:2013-02-22 19:19:41

标签: java applet

为了简化,我想设计一个显示带有三个相邻按钮的交通灯的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 ();
    }
}

1 个答案:

答案 0 :(得分: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
}