我是初学者,我想在我运行程序时启动计时器(即当父jFrame出现时)并在5秒后丢弃帧。我想在计时器启动时开始填充虚拟进度条,并将其完全填满,直到计时器熄灭。
答案 0 :(得分:5)
这是您的代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
public class ClosingPanel extends JFrame{
private final Timer every50millis;
public ClosingPanel() {
setTitle("this panel will self-destruct");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JProgressBar progressBar = new JProgressBar(SwingConstants.HORIZONTAL, 0, 100);
add(progressBar);
pack();
every50millis = new Timer(50, new ActionListener() {
private int count=0;
@Override
public void actionPerformed(ActionEvent e) {
count++;
progressBar.setValue(count);
if (count==100) {
shutdown();
}
}
});
every50millis.start();
}
private void shutdown() {
System.err.println("shutting down");
every50millis.stop();
WindowEvent closingEvent = new WindowEvent(ClosingPanel.this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
ClosingPanel panel = new ClosingPanel();
panel.setVisible(true);
}
});
}
}