1
我想用进度条创建一个基本的JDialog,并在完成某些操作时更新该栏。我的代码是:Swing ProgressBar并不总是更新
public class Main {
public static void main(String[] args) {
WikiReaderUI ui = new WikiReaderUI();
SwingUtilities.invokeLater(ui);
}}
和:
public class WikiReaderUI implements Runnable {
private JFrame frame;
protected Document doc;
protected JProgressBar progressBar;
protected int progress;
@Override
public void run() {
frame = new JFrame("Wiki READER");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set up the content pane.
addComponentsToPane(frame.getContentPane());
// Display the window.
frame.setSize(600, 320);
frame.setResizable(false);
frame.setVisible(true);
}
private void addComponentsToPane(Container pane) {
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
addLanguagePanel(pane);
//other panels...irelevant for my problem
addCreationPanel(pane);
}
private void addCreationPanel(Container pane) {
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.ipady = 5;
JButton createDoc = new JButton("Create PDF");
createDoc.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JDialog dlg = new JDialog(frame, "Progress Dialog", true);
progressBar = new JProgressBar(0, 500);
progressBar.setOpaque(true);
dlg.add(BorderLayout.CENTER, progressBar);
dlg.add(BorderLayout.NORTH, new JLabel("Progress..."));
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.setSize(300, 75);
dlg.setLocationRelativeTo(frame);
dlg.setVisible(true);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (progress < 500) {
progressBar.setValue(progress);
progress++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
}
});
infoPanel.add(createDoc, c);
pane.add(infoPanel);
}
当我运行该程序,并单击createDoc按钮,没有更新进度条的对话框中,但如果我关闭对话框,然后点击按钮,进度条正在更新。我知道这是与事件调度线程有关的事情,但我不知道如何更改我的代码,以便始终更新栏。
我也试过用SwingWorker,没有成功。
感谢的建议,但是这一次,当我按下按钮,第一次进度条只更新... – mawus
这意味着它的工作首先点击,以及那是你的原问题。 – Braj
每次按下按钮时进度条都应该有效。我的第一个问题是,它没有在第一次点击更新。现在它只能在第一次点击时工作 – mawus