Lendvay András
Lendvay András

Reputation: 155

Creating a Progress Bar - Refreshing a JDialog

I am trying to implement a progress JDialog in Java. I am parsing files, and I want the JDialog to refresh after I started to parse a new File. My problem is that the JDialog is not refreshing. I have tried to repaint it, or resize it, so it would repaint. I have also tried to remove the label, and add a new one.

The ProgressDialog class:

public class ProgressDialog extends javax.swing.JDialog {
    private JLabel jLabel1;

    public ProgressDialog(Window frame) {
        super(frame);
        this.setResizable(false);
        this.setLocationRelativeTo(frame);
        initGUI();
        //this.setVisible(true);

    }

    private void initGUI() {
        try {
            {
                setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
                getContentPane().setLayout(null);
                {
                    jLabel1 = new JLabel();
                    getContentPane().add(jLabel1);
                    jLabel1.setText("In Progress..");
                    jLabel1.setBounds(12, 12, 215, 52);
                    jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
                }
            }
            this.setSize(255, 114);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setText(String s){
        this.setVisible(true);
        jLabel1.setText(s);
        this.resize(this.getSize());
        this.repaint();
    }
}

How I use it:

ProgressDialog pd = new ProgressDialog(frame);
for(File file:files){
    pd.setText("Parsing " + file + ".");

    ...

}

Upvotes: 1

Views: 1677

Answers (2)

Robin
Robin

Reputation: 36621

You should perform the parsing of the file on a worker thread, and update your progress dialog on the Event Dispath Thread. A few links worth reading:

Upvotes: 4

Guillaume Polet
Guillaume Polet

Reputation: 47637

I am guessing that you are performing the parsing of your files in the EDT (Event Dispatching Thread). But calling repaint() actually pushes an Event on the EventQueue that will be dispatched when your current call on the EDT is done. Since you are blocking the EDT, the repaint only occurs when you have performed all your job and thus you never see a refresh/repaint of your progress bar.

What you should do is use SwingWorker to put your parsing-job in a separate thread and leave the EDT unblocked. There are plenty of examples on how to use SwingWorker on SO or on the Web.

Upvotes: 3

Related Questions