我这里有一个进度条示例:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.border.Border;
public class ProgressSample {
public static void main(String args[]) {
JFrame f = new JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
现在..有没有办法让值从0到100%运行而没有按钮触发它。就像我运行该帧一样,Thread
或Timer
会自动启动。有办法吗?或者我仍然需要一个按钮来触发计时器/线程?
答案 0 :(得分:2)
简单的回答是,是的。
您可以随时更新进度条,只要您在事件调度线程的上下文中执行此操作即可。您需要的是告诉JProgressBar
新值应该是什么的某种方式,但这取决于您要实现的目标。
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.JProgressBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class AutoProgress {
public static void main(String[] args) {
new AutoProgress();
}
private JProgressBar pb;
private int progress;
public AutoProgress() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
pb = new JProgressBar();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(pb);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
progress += 1;
if (progress >= 100) {
progress = 100;
((Timer)e.getSource()).stop();
}
pb.setValue(progress);
}
});
timer.start();
}
});
}
}
您可能还想查看JProgressBar#setIndeterminate
。
您还应该查看How to use Swing Timers