2012-07-02 47 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