Swing ProgressBar并不总是更新

时间:2014-06-09 18:58:31

标签: java swing swingworker jprogressbar

我想创建一个带进度条的基本JDialog,并在完成某些操作时更新栏。我的代码是:

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,但没有成功。

1 个答案:

答案 0 :(得分:0)

启动帖子后显示JDialog

t.start();
dlg.setVisible(true);

使用更适合Swing应用程序的Swing Timer代替Java Timer

了解更多How to Use Swing Timers