Java Swing How to - Display button "Ok" after a certain amount of time for JOptionPane








Question

We would like to know how to display button "Ok" after a certain amount of time for JOptionPane.

Answer

import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Label;
//w w w .j  a v a2s .c o m
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingWorker;

public class Main extends Box {

  public Main() {
    super(BoxLayout.Y_AXIS);

    Box info = Box.createVerticalBox();
    info.add(new Label("Please wait 3 seconds"));
    final JButton continueButton = new JButton("Continue");
    info.add(continueButton);

    JDialog d = new JDialog();
    d.setModalityType(ModalityType.APPLICATION_MODAL);
    d.setContentPane(info);
    d.pack();

    continueButton.addActionListener(e -> d.dispose());
    continueButton.setVisible(false);

    SwingWorker sw = new SwingWorker<Integer, Integer>() {
      protected Integer doInBackground() throws Exception {
        int i = 0;
        while (i++ < 30) {
          System.out.println(i);
          Thread.sleep(100);
        }
        return null;
      }

      @Override
      protected void done() {
        continueButton.setVisible(true);
      }

    };
    JButton button = new JButton("Click Me");
    button.addActionListener(e -> {
      sw.execute();
      d.setVisible(true);
    });
    add(button);
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main());
    frame.setPreferredSize(new Dimension(500, 400));
    frame.pack();
    frame.setVisible(true);
  }
}