*问题已解决 - 感谢您的所有回答,他们非常有帮助!
我正在为学校作业制作一个小型骰子游戏,我遇到了这个问题。我想通过快速循环通过多个骰子图标来模拟骰子的滚动。不过,这本身并不是导致问题的原因。如果我直接在 JFrame 中制作“动画”,它会正确显示。我已经在下面的代码中做到了:
public class Example{
private static ImageIcon die1 = new ImageIcon("terning1.jpg");
private static ImageIcon die2 = new ImageIcon("terning2.jpg");
private static ImageIcon die3 = new ImageIcon("terning3.jpg");
private static ImageIcon die4 = new ImageIcon("terning4.jpg");
private static ImageIcon die5 = new ImageIcon("terning5.jpg");
private static ImageIcon die6 = new ImageIcon("terning6.jpg");
private static JLabel die = new JLabel(die1);
private static Random generator = new Random();
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(die);
frame.pack();
frame.setVisible(true);
for (int i = 0; i < 100; i++) {
int x = generator.nextInt(6) + 1;
switch(x){
case 1 : die.setIcon(die1);
break;
case 2 : die.setIcon(die2);
break;
case 3 : die.setIcon(die3);
break;
case 4 : die.setIcon(die4);
break;
case 5 : die.setIcon(die5);
break;
case 6 : die.setIcon(die6);
break;
}
//Make the loop wait for 50 millis
long a, b;
a = System.currentTimeMillis();
do {
b = System.currentTimeMillis();
} while ((b-a) < 50);
}
}
}
现在效果很好,但显然它只在我第一次打开 JFrame 时才有效。所以我想添加一个按钮,使骰子滚动。但是,如果我添加一个带有 actionlistener 的 JButton,并将 for 循环放在 actionPerformed 方法中,它会暂停程序直到循环完成,并且只显示循环中的最后一个死。例子:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(die);
button.addActionListener(new ButtonListener());
frame.pack();
frame.setVisible(true);
}
private static class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < 100; i++) {
int x = generator.nextInt(6) + 1;
switch (x) {
case 1:
die.setIcon(die1);
break;
case 2:
die.setIcon(die2);
break;
case 3:
die.setIcon(die3);
break;
case 4:
die.setIcon(die4);
break;
case 5:
die.setIcon(die5);
break;
case 6:
die.setIcon(die6);
break;
}
//Make the loop wait for 50 millis
long a, b;
a = System.currentTimeMillis();
do {
b = System.currentTimeMillis();
} while ((b - a) < 50);
}
关于如何解决这个问题的任何提示?预先感谢!