JLabel setIcon 不起作用



我有一个显示硬币图片的程序。当用户点击硬币时,硬币从正面变为反面,反之亦然。这工作正常。 当我想有一个按钮随机翻转硬币次数(在本例中为 3 到 10 次(包括 3 到 10 次)时,就会出现问题。 用于更改图像图标的方法:

flip.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e1) {
playerCoinState = coinState;
System.out.println("Clicked");
int flips = (new Random().nextInt(8)) + 3;
for(int i = 0; i < flips; i++){
try{
Thread.sleep(1000);
}catch(InterruptedException e2){
System.exit(1);
}
System.out.println("Auto Flipped");
changeFace();
}
}
});

这是用于更改JLabel硬币的ImageIcon的方法:

private void changeFace(){
System.out.println("Changing...");
switch(coinState){
case 0:
System.out.println("Coin State 0");
try {
coin.setIcon(new ImageIcon(ImageIO.read(new File("res/Heads.png"))));
} catch (IOException e) {
e.printStackTrace();
}
coinState = 1;
break;
case 1:
System.out.println("Coin State 1");
try {
coin.setIcon(new ImageIcon(ImageIO.read(new File("res/Tails.png"))));
} catch (IOException e) {
e.printStackTrace();
}
coinState = 0;
break;
}
}

JLabel硬币的初始化为:

coin = new JLabel(new ImageIcon("res/Tails.png"));

币状态代表硬币的价值。 0 表示正面,1 表示反面。 playerCoinState用于跟踪玩家在计算机随机掷硬币之前选择的硬币状态。

这个...

for(int i = 0; i < flips; i++){
try{
Thread.sleep(1000);
}catch(InterruptedException e2){
System.exit(1);
}
System.out.println("Auto Flipped");
changeFace();
}

阻止事件调度线程,阻止 UI 在方法退出之前进行更新

您应该尝试改用 SwingTimer,它充当伪循环,但在后台等待规定的时间段,然后在 EDT 上下文中触发时钟周期,从而可以安全地从

coin = new JLabel(new ImageIcon((ImageIO.read(new File("path"))));

使用这个而不是coin.setIcon(new ImageIcon(ImageIO.read(new File("res/Tails.png"))));因此,您每次都创建新的硬币标签。如果您正在使用eclispe和windowbuilder,则可以使用侧边栏上的工具。

MadProgrammer帮助我解决了这个问题。
按钮的新的和改进的 ActionListener 是:

flip.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e1) {
playerCoinState = coinState;
int flips = (new Random().nextInt(10) + 5);
Timer timer = new Timer(400, new ActionListener(){
int counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
if(counter == flips){
((Timer)e.getSource()).stop();
}
changeFace();
counter++;
}
});
timer.start();
}
}); 

再次感谢疯狂程序员=)

最新更新