2015-02-09 41 views
2

我想在執行函數mediaPlayer()之前顯示一個文本。在媒體播放器的執行過程中,我睡着了線程。沒關係,因爲什麼都不需要發生(然後只需要聽)。睡眠一個java線程,但首先更新jFrame

但是,上一個文本:「收聽...」,沒有顯示(除了延遲幾秒鐘)。有沒有辦法在線程進入休眠之前先刷新jFrame?

expText.setText("Listen to the song and give a rating when it finishes."); 

        startButton.setEnabled(false); 


        //play sound 
        try { 
         mediaPlayer(); 
         //wait for the duration of the stimuli 
         Thread.sleep(stimDuration); 
        ... 
+0

是:永遠不要在UI線程上進行長時間運行的操作。在後臺線程上調用'mediaPlayer'或將其重寫爲異步。 – 2015-02-09 19:28:10

+1

你不想把SwingWorker包裝在一個Timer中,這只是......很奇怪。只需使用SwingWorker來播放音頻。看看[這個例子](http://stackoverflow.com/questions/24274997/java-wav-player-adding-pause-and-continue/24275168#24275168) – MadProgrammer 2015-02-09 20:23:47

+0

什麼mediaPlayer和單桅帆船它工作?延遲的目的是什麼? – MadProgrammer 2015-02-09 20:28:44

回答

1

以下結合使用線程和Swing Timer解決了這個問題。

  Thread t2 = new Thread(new Runnable() { 
         public void run() { 
          try { 
           startButton.setEnabled(false); 
           startButton.setVisible(false); 
           buttonsPanel.setEnabled(false); 
           buttonsPanel.setVisible(false); 
           expText.setText("Listen to the song and give a rating when it finishes."); 
          } catch (Exception e1) { 
           e1.printStackTrace(); 
          } 
         } 
        }); 
        t2.start(); 




        Thread t1 = new Thread(new Runnable() { 
         public void run() { 
          // code goes here. 
          try { 
           mediaPlayer(); 
//        Thread.sleep(5000); 


          } catch (Exception e1) { 
           e1.printStackTrace(); 
          } 
         } 
        }); 
        t1.start(); 

        ActionListener taskPerformer = new ActionListener() { 
         public void actionPerformed(ActionEvent evt) { 
          //...Perform a task... 

          resultButtonGroup.clearSelection(); 
          startButton.setEnabled(true); 
          startButton.setVisible(true); 
          buttonsPanel.setVisible(true); 

         } 
        }; 
        Timer timer = new Timer(stimDuration ,taskPerformer); 
        timer.setRepeats(false); 
        timer.start(); 
2

的的setText纔會顯示在EDT渲染另一幀,它不能這樣做,因爲它是stimDuration的時間忙睡覺。

嘗試在單獨的線程上播放聲音,在其他某個線程上播放聲音,檢測聲音何時停止,然後在EDT上執行另一個操作,然後將expText更改回原始文本。

+0

沒有明確定義多線程,沒有辦法解決這個問題嗎?我不是這方面的專家,這就是爲什麼我問。我只是想讓程序稍微等一下。擺動計時器似乎也是一種選擇,但我無法弄清楚。 – dorien 2015-02-09 19:31:13

+0

@dorien也許使用像這樣的東西http://stackoverflow.com/a/782309/3352285來避免顯式創建和處理線程和Runnables自己。 – NESPowerGlove 2015-02-09 19:35:36

+0

謝謝,我剛剛嘗試過,但在done()方法中,我無法訪問我的startButton,因爲它在不同的類中。 – dorien 2015-02-09 19:47:54