是什么导致绿灯保持绿色?

时间:2018-11-28 17:10:20

标签: java swing graphics jframe awt

抱歉,这个愚蠢的问题,是我的作业。我应该制作一个交通信号灯,当按下按钮时,该信号灯会改变灯光。我有一半工作,我遇到的问题是在红色阶段绿色指示灯一直亮着。我在所有三个阶段都做同样的事情,所以我不明白为什么它只在那个阶段有问题。 代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class ButtonPanel extends JPanel {

int presses;

int gy=200;
int yy=130;
int ry=60;
int filly=ry;
int empty1=gy;
int empty2=yy;
private JButton push;
private JLabel label;
Color light=Color.RED;

public ButtonPanel () {
    presses=0;
    push=new JButton("Change Light");



    push.addActionListener(new ButtonListener());
    add(push);


    setBackground(Color.white);
    setPreferredSize(new Dimension(300,400));
}
public void paint(Graphics g) {
    super.paint(g);
    setBackground(Color.WHITE);

    g.drawOval(120,gy,50,50);
    g.drawOval(120,yy,50,50);
    g.drawOval(120,ry,50,50);
    g.drawRect(95, 50, 100, 210);
    g.setColor(light);
    g.fillOval(120, filly, 50, 50);
    g.setColor(Color.white);
    g.fillOval(120, empty1, 50, 50);
    g.fillOval(120, empty2, 50, 50);



}
public class ButtonListener implements ActionListener{

    public void actionPerformed(ActionEvent e) {
        System.out.println(presses);
        presses++;
        if(presses>2) {
            presses=0;
        }
        if(presses==0) {
            light=Color.red;
            filly=ry;
            System.out.println("check");
            empty1=gy;
            System.out.println("check");
            empty1=yy;
            repaint();
        }
        if(presses==1) {
            light=Color.yellow;
            filly=yy;
            empty1=ry;
            empty2=gy;
            repaint();
        }
        if(presses==2) {
            light=Color.green;
            filly=gy;
            empty1=ry;
            empty2=yy;
            repaint();
        }

        }

    }
}

如果要编译,则为框架和主要方法部分:

import javax.swing.JFrame;
public class TrafficFrame {

public static void main(String[] args) {
    JFrame frame= new JFrame("Traffic Light");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ButtonPanel panel=new ButtonPanel();
    frame.getContentPane().add(panel);

    frame.pack();
    frame.setVisible(true);

}

}

1 个答案:

答案 0 :(得分:2)

在我看来像是一个简单的错字。在该if块中,您要两次设置empty1,而不要设置empty2