- 不要打电话updateUI,除非您要安装外观,否则不会按照您认为的那样做(这是非常低效的)
- 不要每次都重新构建UI,这是很费时间的工作,这会使动画看上去静止不动和交错,并且可能闪烁很多。相反,只需更新icon标签的属性
- 使用单个Timer,允许它增加一个计数器,这样您就知道它被调用了多少次,并在每个刻度上更新了骰子滚动和计数器。
可以将其Timer视为一种循环,在每次迭代(滴答)中,您
需要做一些事情(例如增加计数器)
(注意-当模具看起来已经“停滞”时,是因为图像显示的顺序要多于一次。您可以通过将所有图像放入List并使用来解决此问题Collections.shuffle。执行三遍,然后添加结果到另一个List应该给你24个无重复的序列(好的,它“可能”在边界上重复,但是最好使用Math.random;))
import java.awt.Dimension;import java.awt.EventQueue;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.Timer;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } Jframe frame = new Jframe("Testing"); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private BufferedImage[] dice = new BufferedImage[6]; private JLabel die; public TestPane() { try { BufferedImage img = ImageIO.read(new File("/Users/swhitehead/documents/Die.png")); int width = 377 / 6; for (int index = 0; index < 6; index++) { dice[index] = img.getSubimage(width * index, 0, width, width); } } catch (IOException ex) { ex.printStackTrace(); } setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; die = new JLabel(new ImageIcon(dice[0])); add(die, gbc); JButton roll = new JButton("Roll"); add(roll, gbc); roll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { roll.setEnabled(false); Timer timer = new Timer(250, new ActionListener() { private int counter; private int lastRoll; @Override public void actionPerformed(ActionEvent e) { if (counter < 20) { counter++; lastRoll = (int)(Math.random() * 6); System.out.println(counter + "/" + lastRoll); die.setIcon(new ImageIcon(dice[lastRoll])); } else { lastDieRollWas(lastRoll); ((Timer)e.getSource()).stop(); roll.setEnabled(true); } } }); timer.start(); } }); } protected void lastDieRollWas(int roll) { System.out.println("You rolled " + (roll + 1)); } @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } }}


