我想制作一个Swing版本的TimeBomber,这意味着当时间计算到1时炸弹会爆炸!我有两个图像,images.png用于正常状态下的炸弹,bomber.jpg用于炸毁炸弹。显然,当i == 1时,我需要将images.png(已经在JLabel中)更改为bomber.jpg;但我不知道如何更改ImageIcon中的pic位置内容,并且随着更改发生在匿名内部类中,因此更改值变得困难,因为除非您调用函数,否则最终类型var不可修改。
public class TimeBomber {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//create Jframe
JFrame app = new JFrame("Time Bomber");
//create JPanel
final JPanel panel = new JPanel();
//JLabel with first Picture
JLabel pic = new JLabel(new ImageIcon("images.png"));
pic.setSize(100, 100);
//Label for displaying time digit
final JLabel label = new JLabel("");
label.setLocation(200, 250);
//create another thread
Thread time = new Thread(){
public void run(){
for(int i=10; i>0; i--){
if(i==1){
JLabel picSecond = new JLabel(new ImageIcon("Bomber.jpg"));
//<--Fact is I dont want to create another JLabel, I want to modify the pic location content in JLabel pic.
picSecond.setSize(100, 100);
panel.add(picSecond);
}
label.setText("Time: "+i);
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
//add every component to where it belongs
panel.add(pic);
panel.add(label);
app.add(panel);
app.setSize(300, 400);
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
time.start();
}
}
答案 0 :(得分:3)
将代码包装在SwingUtilities.invokeAndWait()(或SwingUtilities.invokeLater())中
if(i==1){
JLabel picSecond = new JLabel(new ImageIcon("Bomber.jpg"));//<--Fact is I dont want to create another JLabel, I want to modify the pic location content in JLabel pic.
picSecond.setSize(100, 100);
panel.add(picSecond);
}
label.setText("Time: "+i);
为了避免重新创建JLabel,请将其作为课程的一部分。字段并只添加到面板一次。然后使用picSecond.setIcon()
更新图片。
顺便说一句,最好有各种图像缓存,以避免每一步都重现图像。