按下按钮启动计时器

时间:2016-03-04 13:55:46

标签: java netbeans timer

在java中我正在与交通信号灯交叉。交通信号灯由定时器操作,但定时器始终运行。是否有可能使定时器仅在汽车(或按钮)等待(或按下)灯时工作?

我使用的代码:

public class X extends Applet implements Runnable {

  Thread t = null;
  int state;
  boolean stopFlag;
  int light1 = 100;
  String s;
  boolean diff;
  Color c1 = Color.black;
  Color c2 = Color.black;
  Color c3 = Color.black;

  @Override
  public void start() {
    t = new Thread(this);
    stopFlag = false;
    c1 = Color.black;
    c2 = Color.black;
    c3 = Color.black;
    t.start();
    s = "abc";
    diff = s.equalsIgnoreCase("abc");
  }

  @Override
  public void run() {
    while (true) {
      try {
        if(light1>=0)  light1-=1;
        else           light1=100;

        if(light1>=60) c1 = Color.red;
        else           c1 = Color.black;

        if(light1<60)  c2 = Color.green;

        if(light1<20)  c2 = Color.black;

        if(light1<20)  c3 = Color.orange;
        else           c3 = Color.black;

        Thread.sleep(100);
        repaint();
      }
      catch(Exception e) {}
    }
  }

  @Override
  public void paint(Graphics g) {
    //applet size
    this.setSize(1000,800);

    //background
    Color grass = new Color(50,205,50);
    g.setColor(grass);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());

    //road
    g.setColor(Color.BLACK);
    g.fillRect(0, 300, 1000, 150);
    g.fillRect(425, 0, 150, 1000);

    //crosswalks
    g.setColor(Color.WHITE);
    for(int var = 310; var <= 430; var += 20) {
      g.fillRect(585, var, 50, 10);
    }

    for(int var = 310; var <= 430; var += 20) {
      g.fillRect(365, var, 50, 10);        
    }    

    for(int var2 = 435; var2 <= 555; var2 += 20) {
      g.fillRect(var2, 240, 10, 50);        
    }

    for(int var2 = 435; var2 <= 555; var2 += 20) {
      g.fillRect(var2, 460, 10, 50);        
    }

    //sidewalks
    Color wandel = new Color(169,169,169);
    g.setColor(wandel);
    g.fillRect(585, 0, 50, 300);
    g.fillRect(585, 450, 50, 350);
    g.fillRect(0, 240, 425, 50);
    g.fillRect(0, 460, 425, 50);        
    g.fillRect(575, 460, 425, 50);
    g.fillRect(575, 240, 425, 50);
    g.fillRect(365, 0, 50, 300);
    g.fillRect(365, 450, 50, 425);

    //trafficlight frame
    g.setColor(Color.GRAY);
    g.fillOval(645, 525, 25, 25);
    g.fillRect(645, 538, 25, 60);

    //trafficlight lights
    g.setColor(c1);
    g.fillOval(653,535,10,10);
    showStatus(diff+"Timer:"+light1);
    g.setColor(c2);
    g.fillOval(653,575,10,10);
    showStatus(diff+"Timer:"+light1);
    g.setColor(c3);
    g.fillOval(653,555,10,10);
    showStatus(diff+"Timer:"+light1);
  }     
}

0 个答案:

没有答案