2012-07-02 42 views
0

我有一個包含面板的mainFrame。只要應用程序正在運行,我想在此面板中更改標籤圖像的線程...在JFrame中使用線程

當我創建實現runnable的面板,然後在主機中創建此面板的實例時,應用程序會進入無限循環......我的代碼如下:

public mainFrame() 
{ 
    BanerPanel baner = new BanerPanel(); 
    baner.run(); 
} 

public class Banner_Panel extends JPanel implements Runnable { 

    public Banner_Panel() { 
     initComponents(); 
     imgPath = 2; 
     imgLbl = new JLabel(new ImageIcon(getClass().getResource("/Photos/banner_4-01.png"))); 
     add(imgLbl); 
     //run(); 
    } 
    @Override 
    public void run() { 
     while(true) 
     { 
      try { 
      while (true) { 
       Thread.sleep(3000); 
       switch(imgPath) 
       { 
        case 1: 
         imgLbl.setIcon(new ImageIcon(getClass().getResource("/Photos/banner_4-01.png"))); 
         imgPath = 2; 
         break; 
        case 2: 
         imgLbl.setIcon(new ImageIcon(getClass().getResource("/Photos/banner_1-01.png"))); 
         imgPath = 3; 
         break; 
        case 3: 
         imgLbl.setIcon(new ImageIcon(getClass().getResource("/Photos/banner_2-01.png"))); 
         imgPath = 4; 
         break; 
        case 4: 
         imgLbl.setIcon(new ImageIcon(getClass().getResource("/Photos/banner_3-01.png")));  
         imgPath = 1; 
         break; 
       } 

      } 
      } catch (InterruptedException iex) {} 
     } 
    } 
+0

@ user1329572多數民衆贊成在權利,爲我工作,但ImageIcon必須沖洗() – mKorbel

回答

8
  • 不要在後臺線程調用JLabel#setIcon(...),因爲這必須Swing事件線程或EDT上調用。相反,爲什麼不簡單地使用Swing Timer呢?
  • 此外,沒有必要不斷從磁盤讀取圖像。相反,請一次讀取圖像,並將ImageIcons放在一個數組或ArrayList<ImageIcon>中,並簡單地遍歷Swing Timer中的圖標。
  • 您的代碼實際上並不使用後臺線程,因爲您直接在您的Runnable對象上調用run(),該對象根本沒有執行任何線程。請閱讀threading tutorial以瞭解如何使用Runnables和Threads(提示您在Thread上調用start())。

例如

// LABEL_SWAP_TIMER_DELAY a constant int = 3000 
javax.swing.Timer myTimer = new javax.swing.Timer(LABEL_SWAP_TIMER_DELAY, 
     new ActionListener(){ 
    private int timerCounter = 0; 

    actionPerformed(ActionEvent e) { 
    // iconArray is an array of ImageIcons that holds your four icons. 
    imgLbl.setIcon(iconArray[timerCounter]); 
    timerCounter++; 
    timerCounter %= iconArray.length; 
    } 
}); 
myTimer.start(); 

如需更多信息,請查看Swing Timer Tutorial

+0

什麼是搖擺計時器?並可以用一些代碼支持我... – BDeveloper

+1

+1;不能同意更多 – GETah

+0

我duno爲什麼我總是以-1的票數......是因爲我遲到的迴應還是什麼?其實我在一段時間後檢查答案.. – BDeveloper