I want to create a basic JDialog with a progress bar, and to update the bar when some operations are done. My code is:
public class Main {
public static void main(String[] args) {
WikiReaderUI ui = new WikiReaderUI();
SwingUtilities.invokeLater(ui);
}}
and:
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);
}
When I run the program and click the createDoc button, the progress bar is not updated in the dialog, but if I close the dialog and click the button again, the progress bar is updating. I know it's something related with event dispatch thread, but I don't know how to change my code in order to always update the bar.
I've also tried with a SwingWorker, without success.