簡體   English   中英

Thread.sleep()來擺動定時器轉換

[英]Thread.sleep() to swing Timer conversion

我正在嘗試實現Thread.sleep(6000)行,但似乎凍結在applet中。 當我嘗試使用Timers時,我不確定如何使用,因為我對事件監聽器不是很好。 我基本上嘗試在用戶單擊enter按鈕后每6秒調用一次方法fetchUrl() 我該如何實現呢?

public void init() {

    c = getContentPane();
    c.setLayout(flow);
    c.setBackground(forum); 

    question.setForeground(Color.white);
    question.setFont(tnr);  
    question2.setForeground(Color.white);
    question2.setFont(tnr);
    result.setForeground(Color.white);
    result.setFont(tnr);    
    resp.setBorder(BorderFactory.createBevelBorder(0));
    timeLength.setBorder(BorderFactory.createBevelBorder(0));
    c.add(question);    
    c.add(resp);
    c.add(question2);
    c.add(timeLength);
    c.add(enter);
    c.add(result);
    resp.requestFocus();
    enter.addActionListener(this);
    t = new Timer(DELAY, this);
    t.setInitialDelay(DELAY);

}

public void actionPerformed(ActionEvent e) {
    final String n1;
    int timeMin, timeSec, count = 0, maxCount;
    timeMin = Integer.parseInt(timeLength.getText());
    timeSec = timeMin * 60;
    maxCount = (int)(timeSec/6);
    if (e.getSource() == enter) {         //user clicks enter
        n1 = resp.getText();
        while (count < maxCount) {
            fetchUrl(n1);                 //this method called every 6 seconds
            t.start();
            count++;
        }

    }
}

首先,我將首先分離TimerActionListenerJButton

第二,沒有任何事情與計時器邏輯上發生,因為你用按鈕源檢查吞下它。

第三,你應該了解計時器的工作原理。 基本上對於每個“tick” (在你的情況下為6秒),調用定時器ActionListener的actionPerformed 因此,如果你想要調用fetch()方法,那么你應該在Timer的actionPerformed中看到/訪問它。

按鈕的ActionListener應該只處理我相信的計時器的啟動。 所以只需將聽眾分開。 為每個人提供一個匿名的ActionListener ,而不需要讓該類實現ActionListener

例如

timer = new Timer(DELAY, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        // do some stuff every six seconds
        fetchURL();
    }
});

enter = new JButton(...);
enter.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        timer.start();
    }
});

如果你想為計時器提供一些自動停止功能,你可以做類似的事情

timer = new Timer(DELAY, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        if (someStoppingCondition()) {
            timer.stop();
        } else {
            // do some stuff every six seconds
            fetchURL();
        }
        // do some stuff every six second
    }
});

用戶每6秒鍾點擊一次按鈕后需要調用一個方法,但是你還沒有說過要調用它的次數。

無限次,嘗試以下內容,

while(true){

     new Thread(){
          @Override
          public void run(){
                try{
                       Thread.sleep(6000);
                       fetchUrl(n1);
                }catch(InterruptedException e){}
          }

     }.start();

}

如果您將在applet中使用Thread.sleep(),那么您的applet將被掛起6秒,因此為它創建一個新線程。

暫無
暫無

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

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