如何为 ActionListener 设置定时器
How to set a timer to an ActionListener
我制作了一款老虎机游戏。在我的老虎机游戏中,我有一个按钮,按下时会生成三个随机图像。我希望这个按钮在按下 5 秒后生成三个随机图像。这是我的按钮代码及其动作侦听器。
b1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
randomPictureGenerator(evt);
repaint();
}
});
private void randomPictureGenerator(java.awt.event.ActionEvent evt) {
this.run();
}
public void run() {
pictures = new ArrayList<>();
pictures.add(new File("question.png"));
pictures.add(new File("banana.png"));
pictures.add(new File("chocolate.png"));
pictures.add(new File("icecream.png"));
pictures.add(new File("bell.png"));
pictures.add(new File("apple.png"));
pictures.add(new File("money.png"));
pictures.add(new File("number-7.png"));
pictures.add(new File("necklace.png"));
pictures.add(new File("gloves.png"));
int number = rand.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label.setIcon(new ImageIcon(pictures.get(number).getAbsolutePath()));
int number2 = rand2.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label2.setIcon(new ImageIcon(pictures.get(number2).getAbsolutePath()));
int number3 = rand3.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label3.setIcon(new ImageIcon(pictures.get(number3).getAbsolutePath()));
}
这就是线程发挥作用的地方!从编译器错误到异常处理、线程和线程中断,您需要阅读很多东西。但这可以通过将此代码放在 运行() 方法中来完成您想做的事情。
try {
Thread.sleep(5000); //5000 milliseconds is five seconds.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
我制作了一款老虎机游戏。在我的老虎机游戏中,我有一个按钮,按下时会生成三个随机图像。我希望这个按钮在按下 5 秒后生成三个随机图像。这是我的按钮代码及其动作侦听器。
b1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
randomPictureGenerator(evt);
repaint();
}
});
private void randomPictureGenerator(java.awt.event.ActionEvent evt) {
this.run();
}
public void run() {
pictures = new ArrayList<>();
pictures.add(new File("question.png"));
pictures.add(new File("banana.png"));
pictures.add(new File("chocolate.png"));
pictures.add(new File("icecream.png"));
pictures.add(new File("bell.png"));
pictures.add(new File("apple.png"));
pictures.add(new File("money.png"));
pictures.add(new File("number-7.png"));
pictures.add(new File("necklace.png"));
pictures.add(new File("gloves.png"));
int number = rand.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label.setIcon(new ImageIcon(pictures.get(number).getAbsolutePath()));
int number2 = rand2.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label2.setIcon(new ImageIcon(pictures.get(number2).getAbsolutePath()));
int number3 = rand3.nextInt((pictures.size() -1/*Max*/ - 0/*min*/) + 1) + 0/*Min*/;
this.label3.setIcon(new ImageIcon(pictures.get(number3).getAbsolutePath()));
}
这就是线程发挥作用的地方!从编译器错误到异常处理、线程和线程中断,您需要阅读很多东西。但这可以通过将此代码放在 运行() 方法中来完成您想做的事情。
try {
Thread.sleep(5000); //5000 milliseconds is five seconds.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}