我有3 Thread.sleep(1000);
s,我希望在1秒(1000毫升)后逐个显示。 find_hi-again
无效。我不知道,完成任务后将显示三个JLabel(3秒后同时显示3个JLabel)。我该如何解决?定时器可以延迟吗?
答案 0 :(得分:1)
你可以试试这个
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
答案 1 :(得分:1)
以下是我对此的看法:
package demo.javase.swing;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ThreeJLabelsDemo extends JPanel {
private Timer timer;
private JButton startButton;
private int count;
public ThreeJLabelsDemo() {
super(new FlowLayout());
startButton = new JButton("Add 3 JLabels");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
timer.start();
}
});
add(startButton);
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
add(new JLabel("Label" + count++));
revalidate();
repaint();
timer.stop();
if (count < 3) {
timer.restart();
} else {
startButton.setEnabled(true);
count = 0;
}
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Three JLabels Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ThreeJLabelsDemo());
frame.setSize(new Dimension(640, 480));
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
我相信在这种情况下,您必须使用javax.swing.Timer
,因为Thread.sleep(long)
会阻止该应用。