2014-06-22 34 views
0

我想使用GUI/Swing爲即將到來的考試做一個輪盤遊戲的模擬。我有兩個類,一個稱爲GUI,實際上是用於組件的代碼,例如JFrame,JOptionPane,JButton等。另一個類擴展了Thread,應該在一個小JLabel上顯示隨機數,並且run方法會是這樣的:Java GUI/Swing,停止線程,在類之間傳遞整數

public void run() { 
    int k = 0; 
    for (int i = 0; i < 50; i++) { 
     k = (new Random().nextInt(37)); 
     label.setText(k + " "); 
     label.setFont(new Font("Tahoma", Font.BOLD, 56)); 
     label.setForeground(Color.yellow); 
     try { 
      sleep(50); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    }  
} 

而在GUI類我只想把從上述循環的最後一次迭代的數量,然後把它傳遞給新的int,其中我會在以後的使用GUI類。 任何想法?

+0

使用Swing的計時器作爲@Braj建議(1+到他的答案)。另外,您幾乎從不想擴展Thread類。如果您需要使用基本的線程,並且絕對不能使用Swing Timer或SwingWorker,那麼您希望您的類實現Runnable,而不是擴展Thread。 –

回答

2

使用Swing Timer而不是Thread.sleep有時會掛起整個swing應用程序。

請看看How to Use Swing Timers

Timer timer = new Timer(50, new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent arg0) {    
     //next call from here 
    } 
}); 
timer.setRepeats(false); 
timer.start(); 

我只想把從上述循環的最後一次迭代的數量,然後把它傳遞給新的int,這是我」 m將在後面的GUI類中使用。

只需在另一個接受int的類中創建一個方法(setter),並從上一次調用該類時調用它。


示例代碼:

private int counter = 0; 
private Timer timer; 
... 

final JLabel label = new JLabel(); 
label.setFont(new Font("Tahoma", Font.BOLD, 56)); 
label.setForeground(Color.yellow); 
Thread thread = new Thread(new Runnable() { 
    public void run() { 

     timer = new Timer(50, new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (counter++ < 50) { 
        int k = (new Random().nextInt(37)); 
        label.setText(k + " "); 
       } else { 
        timer.stop(); 
        label.setText("next call"); 
       } 

      } 
     }); 
     timer.setRepeats(true); 
     timer.start(); 
    } 
}); 

thread.start(); 

快照:

enter image description here