我正在使用JLabel创建动画,
public void updateLabels() {
label.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageCALA,300,300)));
label_1.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageStates,300,300)));
label_2.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imageStrategies,300,300)));
label_3.setIcon(new ImageIcon(new Paint().getScaledImage(paint[currentIndexLabel].imagekD,300,300)));
currentIndexLabel++;
}
Run Code Online (Sandbox Code Playgroud)
我有一个更新标签的按钮
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
while (currentIndexLabel != paint.length-1) {
updateLabels();
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何等待,例如1000毫秒,直到下一次改变.当我添加这个:
try { Thread.sleep(1000); } catch (Exception e){}
Run Code Online (Sandbox Code Playgroud)
进入我的ActionListener:
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
while (currentIndexLabel!=paint.length-1) {
updateLabels();
try { Thread.sleep(1000); } catch (Exception e){}
}
}
});
Run Code Online (Sandbox Code Playgroud)
它不起作用.它只是停了一会儿,我看不到第一帧和最后一帧之间的变化.是否可以在不停止程序的情况下等待1000毫秒?当我删除while循环并尝试部分,然后单击我的按钮时,它变化很好......
我怎样才能做到这一点?
Thread#sleep在主线程中的swing应用程序中使用方法将导致GUI冻结(因为线程休眠,事件不会发生).Thread#sleepswing应用程序中的方法只允许由SwingWorkers使用,这在他们的#doInBackround方法中.
为了在挥杆应用程序中等待(或定期执行某些操作),您将不得不使用Swing Timer.看看我做的一个例子:
import java.awt.FlowLayout;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer; //Note the import
public class TimerExample extends JFrame {
private static final int TIMER_DELAY = 1000;
private Timer timer;
public TimerExample () {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 200);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
timer = new Timer(TIMER_DELAY, e -> {
System.out.println("Current Time is: " + new Date(System.currentTimeMillis()));
});
//timer.setRepeats(false); //Do it once, or repeat it?
JButton button = new JButton("Start");
button.addActionListener(e -> timer.start());
getContentPane().add(button);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TimerExample().setVisible(true));
}
}
Run Code Online (Sandbox Code Playgroud)
按下"开始"按钮后输出:
当前时间是:2月25日星期一13:30:44 EET 2019
当前时间是:2月25日星期一13:30:45 EET 2019
当前时间是:2月25日星期一13:30:46 EET 2019
正如您所看到的,Timer的动作侦听器每秒都会触发.
所以在你的情况下:
timer = new Timer(TIMER_DELAY, e -> {
if (currentIndexLabel != paint.length-1) {
upateLabels();
timer.restart(); //Do this check again after 1000ms
}
});
button.addActionListener(e -> timer.start());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |