Java Swing Timer Loop

时间:2015-02-10 12:51:59

标签: java swing loops timer

想象一组数字。特定于数字的按钮,必须闪烁。我必须通过阵列。现在摆动计时器闪烁一个按钮确定,但如果我尝试将for(int I=0;i<array.length;i++)循环转到下一个按钮 - 计时器不会这样做。任何帮助,将不胜感激。谢谢。这是我现在的代码:

Timer startGame = new Timer(1000, new ActionListener() {
        int colorPlay = 1;//which sqaure to blink
        int blinkingState = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (blinkingState < 2) {
                int i = blinkingState % 2;
                switch (i) {
                    case 0:
                        if (colorPlay == 1) {
                            greenButton.setBackground(Color.green);
                        } else if (colorPlay == 2) {
                            redButton.setBackground(Color.red);
                        } else if (colorPlay == 3) {
                            blueButton.setBackground(Color.blue);
                        } else if (colorPlay == 4) {
                            yellowButton.setBackground(Color.yellow);
                        }
                        break;
                    case 1:
                        if (colorPlay == 1) {
                            greenButton.setBackground(lightGreen);
                        } else if (colorPlay == 2) {
                            redButton.setBackground(lightRed);

                        } else if (colorPlay == 3) {
                            blueButton.setBackground(lightBlue);
                        } else if (colorPlay == 4) {
                            yellowButton.setBackground(lightYellow);
                        }
                        break;
                }//switch ends
                blinkingState++;
            }//if blinking<2 ends
        }//actionPerformed ends
    });//timer ends

1 个答案:

答案 0 :(得分:1)

你的逻辑似乎有缺陷。你想要的是:

  • 闪烁绿灯
  • 等待
  • 闪烁红灯
  • 等待
  • 闪烁黄灯

眨眼是

  • 设置常规背景颜色
  • 等待
  • 设置浅色背景色

这意味着您可能最好使用两个Timer实例。

Timer lightTimer = new Timer( 2000, new ActionListener(){
  private int lightCounter = 0;
  @Override
  public void actionPerformed(ActionEvent e){
    switch( lightCounter ){
      case ...:
      final JButton lightButton = ...;
      lightButton.setBackground( regularColour );
      Timer blinkingTimer = new Timer( 1000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
          lightButton.setColor( lightColour );
        }
      }
      blinkingTimer.setRepeats( false );
      blinkingTimer.start();
    }
    lightCounter++;
    if ( lightCounter == numberOfLights ){
      ((Timer)e.getSource()).stop();
    }
  }
} );
lightTimer.setRepeats( true );
lightTimer.start();

上述代码中的某些内容应该这样做。请注意:

  • 我使用第二个计时器将闪烁的灯光切换回之前的状态(BlinkingTimer变量)
  • BlinkingTimer使用setRepeats( false ),因为它只需要触发一次
  • LightTimer使用setRepeats( true ),因为它需要执行多次,并在所有灯光闪烁后自动关闭