我搜索了这个问题,发现了一些文档,但是它们对我来说太复杂了。
我只想简单地使进度条在活动期间起作用,而不是在那之后。
在我提供的示例代码中,进度条在运行方法完成后才起作用,而不是在此期间起作用。当运行方法运行时,如何更改此代码以更新正在更新的进度条?
我想我必须创建一个新线程来处理长时间运行的方法,但是我不知道该怎么做?
public class Gui extends JFrame {
private JProgressBar progressBar;
private JButton button;
public Gui() throws HeadlessException {
super("Progress bar");
setSize(500, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(resPan());
}
private JPanel resPan() {
JPanel resPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
resPan.setPreferredSize(new Dimension(500, 100));
progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(180, 40));
button = new JButton("Action");
button.setPreferredSize(new Dimension(80, 40));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
progressBar.setIndeterminate(true);
run();
}
});
resPan.add(button);
resPan.add(progressBar);
return resPan;
}
private void run() {
try {
Thread.sleep(4000);
//progressBar.setIndeterminate(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
是的,您必须创建一个新线程。否则,Swing无法显示任何新内容(例如,更新进度条),因为Swing的线程仍在忙于您的run方法。一种简单的方法是:
public void actionPerformed(ActionEvent arg0) {
progressBar.setIndeterminate(true);
new Thread(new Runnable() {
@Override
public void run() {
// do the long-running work here
// at the end:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setIndeterminate(false);
}
);
}
).start();
}
请注意,必须将progressBar声明为final,以便在线程的可运行内部使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句