Java Swing How to - Hide JProgressBar until told to show








Question

We would like to know how to hide JProgressBar until told to show.

Answer

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from  w  w  w. j  a va  2s. c o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class Main {
  public static void main(String[] arguments) {
    JPanel panel = new JPanel(new BorderLayout());
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.setBounds(20, 20, 200, 200);
    frame.setVisible(true);

    JProgressBar progressBar = new JProgressBar();
    progressBar.setIndeterminate(true);
    progressBar.setVisible(false);
    JButton loadButton = new JButton("Load memberlist");
    loadButton.setEnabled(true);
    loadButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        new Thread(new Runnable() {
          @Override
          public void run() {
            progressBar.setVisible(true);
            // do my stuff here...
            try {
              Thread.sleep(2000);
            } catch (Exception e) {
              e.printStackTrace();
            }
            progressBar.setVisible(false);
          }
        }).start();
      }
    });
    JPanel container = new JPanel(new FlowLayout());
    container.add(loadButton);
    container.add(progressBar);
    panel.add(container);
  }
}