簡體   English   中英

Java Swing計時器循環

[英]Java Swing Timer Loop

想象一個數字數組。 特定號碼特定按鈕,該按鈕必須閃爍。 我必須遍歷數組。 現在,swing計時器會按一個按鈕閃爍一次,但是如果我嘗試將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

您的邏輯似乎有問題。 您想要的是:

  • 閃爍綠燈
  • 等待
  • 閃爍紅燈
  • 等待
  • 閃爍黃燈

眨眼的地方

  • 設置常規背景色
  • 等待
  • 設置淺色背景顏色

這意味着您最好使用兩個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 ) ,並在所有指示燈閃爍后自動關閉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM