如何在java JPanel中禁用系统几秒钟



我是新来的图形,我试图禁用代码几秒钟(没有sleep()方法)

public class MainClass
{ 
public static void main(String args[]) 
{ 
JPanel p = new JPanel();
JFrame f = new JFrame("wait");
f.setSize(600,600);
f.setVisible(true);
JLabel l = new JLabel("GET READY");
p.add(l);
l.setBounds(0,0,200,200);

// wait here

for(int i = 0;i<2;i++) {
l.setText(String.valueOf(i));
// wait here again:)
f.repaint();
}

f.add(p);
} 
} 

Background, TL;DR

Swing是单线程的,不是线程安全的。因此,使用Thread.sleep或循环之类的东西是行不通的。

在大多数情况下,最好的解决方案是使用SwingTimer,参见如何使用Swing计时器了解更多细节。

Timer是一个很好的方式来引入回调发生在未来的某个点,他们可以被用来运行一次或无限(直到你停止它)。

如果您需要等待某些操作完成,则会变得稍微复杂一些。在这些情况下,你应该考虑使用Worker线程和SwingWorker,它们可以更容易地执行事件调度线程的功能(有关详细信息,请参阅事件调度线程),但提供了将信息重新同步回EDT的功能。

SwingTimer示例

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {
private JLabel label;
private Timer timer;
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel("Please wait");
add(label);
}
@Override
public void addNotify() {
super.addNotify();
// This is all just so we can allow the UI to stablise
// on the screen
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
startWaiting();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void startWaiting() {
if (timer != null && timer.isRunning()) {
return;
}
timer = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timer = null;
label.setText("Thanks for waiting");
}
});
timer.setRepeats(false);
timer.start();
}
}
}

最新更新