我有一个包含面板的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) {}
}
}
答案 0 :(得分:8)
JLabel#setIcon(...)
,因为必须在Swing事件线程或EDT上调用它。相反,为什么不简单地使用Swing Timer呢? ArrayList<ImageIcon>
中,然后简单地遍历Swing Timer中的图标。run()
,而该对象根本没有执行任何线程。请阅读threading tutorial以了解如何使用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();
有关详情,请查看Swing Timer Tutorial。