簡體   English   中英

如何停止匿名類內的Swing計時器?

[英]How to stop Swing timer inside the anonymous class?

我正在做一個猜謎游戲,但是我在Swing計時器中遇到了問題,因為當我輸入IF語句時我無法停止它。 這是我遇到問題的代碼部分。

continueButton.addActionListener(new  ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        f.add(firstPicblur);
        f.invalidate();
        f.remove(loadingEffectBtn);
        f.setVisible(true);
        f.repaint(); 
        Timer tt = new Timer(100, new ActionListener() {                
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                f.add(firstPiclabelA,BorderLayout.NORTH);
                f.invalidate();
                f.remove(loadingEffect);
                f.setVisible(true);
                f.repaint();
                score01.setText("Score: " + gScore);
                gScore--;                     
            }
        });
        tt.start();
        tt.setRepeats(true); 
        if(gScore == 980){
            tt.stop();

附言:這是我猜游戲中即時解決的最后一個問題,在此之后一切都會好起來的。

我在評論中誤導了您。 而不是使tt成為最終的,而是使其成為封閉類的成員。 這是一個例子:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TimerTest extends JFrame {

    private JLabel label = new JLabel("default");
    private Timer timer;   
    private int gScore = 985;

    public TimerTest() {
        add(label);
        pack();

        timer = new Timer(100, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                gScore--;
                if (gScore == 980) {
                    timer.stop();
                }
                label.setText(String.valueOf(gScore));
            }
        });
        timer.setRepeats(true);
        timer.start();

        setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TimerTest test = new TimerTest();
                test.setVisible(true);
            }
        });
    }

}

您只需要調用它的構造函數一次,然后依靠它的start()stop()方法,因此您的代碼應類似於以下內容:

continueButton.addActionListener(new  ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        f.add(firstPicblur);
        f.invalidate();
        f.remove(loadingEffectBtn);
        f.setVisible(true);
        f.repaint(); 
        tt.start();
}

Timer是動作事件的來源,因此,如果不想將其設為類的字段,則可以使用它:

@Override
public void actionPerformed(ActionEvent e) {
    ...
    gscore--;
    if (gScore == 980) {
        ((Timer) e.getSource()).stop();
    }
}

暫無
暫無

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

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