在JFrame中使用线程

BDe*_*per 0 java swing multithreading jframe

我有一个包含面板的mainFrame.我想在这个面板中一个线程,只要应用程序正在运行,它就会改变标签图像...

当我创建实现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) {}
        }
    }
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 8

  • 不要JLabel#setIcon(...)在后台线程中调用,因为必须在Swing事件线程或EDT上调用它.相反,为什么不简单地使用Swing Timer呢?
  • 此外,无需从磁盘中连续读取图像.相反,一次读取图像并将ImageIcons放在一个数组中,或者ArrayList<ImageIcon>简单地遍历Swing Timer中的图标.
  • 您的代码实际上不使用后台线程,因为您run()直接调用Runnable对象,而该对象根本没有执行任何线程.请阅读线程教程,了解如何使用Runnables和Threads(提示您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();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看Swing Timer教程.