如何在JavaSwing应用程序中添加一个简单的延迟?
我想知道如何在Java中的Swing应用程序中添加时间延迟,我使用了如何在JavaSwing应用程序中添加一个简单的延迟?,java,multithreading,swing,timer,swingworker,Java,Multithreading,Swing,Timer,Swingworker,我想知道如何在Java中的Swing应用程序中添加时间延迟,我使用了Thread.sleep(time),还使用了SwingWorker,但它不起作用。以下是我的部分代码: switch (state) { case 'A': if (charAux == 'A') { state = 'B'; //Here's where I'd like to add a time delay
Thread.sleep(time)
,还使用了SwingWorker,但它不起作用。以下是我的部分代码:
switch (state) {
case 'A':
if (charAux == 'A') {
state = 'B';
//Here's where I'd like to add a time delay
jLabel13.setForeground(Color.red);
break;
} else {
//Here's where I'd like to add a time delay
jLabel12.setForeground(Color.red);
break;
}
}
当我使用SwingWorker时,我希望您能帮助我或解决我的疑问。如果您想指定操作的延迟,您将需要使用。幸好您删除了
线程。睡眠
,因为这将使您的UI在这2秒钟内无响应
您可以启动一个只运行一次的计时器
:
int delay = 2000;
Timer timer = new Timer( delay, new ActionListener(){
@Override
public void actionPerformed( ActionEvent e ){
jLabel12.setForeground( Color.red );
}
} );
timer.setRepeats( false );
timer.start();
请注意,Timer
是一个javax.swing.Timer
,它确保在事件调度线程上调用ActionListener
的actionPerformed
方法,遵守swing线程规则
对于SwingWorker
,这也是可能的,但我会坚持使用计时器来实现这一点。如果要使用SwingWorker
,只需在doInBackground()
方法中使用Thread.sleep
,并在done()
方法中更新JLabel
类似于
class Delay extends SwingWorker<Void, Object> {
@Override
public void doInBackground() {
Thread.sleep( 2000 );
}
@Override
protected void done() {
jLabel12.setForeground( Color.red );
}
}
类延迟扩展SwingWorker{
@凌驾
公共无效doInBackground(){
《睡眠》(2000年);
}
@凌驾
受保护的void done(){
jLabel12.设置前景(颜色为红色);
}
}
下面是一个使用javax.swing.Timer的示例
public class TestBlinkingText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BlinkPane());
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected static class BlinkPane extends JLabel {
private JLabel label;
private boolean state;
public BlinkPane() {
label = new JLabel("Look at me!");
setLayout(new GridBagLayout());
add(label);
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
state = !state;
if (state) {
label.setForeground(Color.RED);
} else {
label.setForeground(Color.BLACK);
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
timer.start();
}
}
}
首先,永远不要在事件调度线程中设置延迟,始终只使用EDT从更新UI。第二,我要看一看动作的延迟,例如2seconds@MadProgrammer但是您提供了一个SSCCE,而我只提供了一些代码片段(无需为此启动IDE),我现在应该已经建立了一个示例目录:P