Java Swing How to - Update JDialog GUI inside a thread








Question

We would like to know how to update JDialog GUI inside a thread.

Answer

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  www.j a va  2  s .c o m
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main implements Runnable, ActionListener {
  JDialog dialog = new JDialog();
  int number = 0;
  JLabel message = new JLabel();
  JButton yes = new JButton("OK"), no = new JButton("Cancel");;
  String messageStr = "number";;
  boolean runProcess = true;

  public Main() {
    dialog.setLayout(new GridLayout());
    yes.addActionListener(this);
    no.addActionListener(this);
    JPanel btnPanel = new JPanel();
    btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
    btnPanel.add(yes);
    btnPanel.add(no);
    dialog.add(message, "Center");
    dialog.add(btnPanel, "South");
    dialog.pack();
    dialog.setVisible(true);
    dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    new Thread(this).start();
  }

  @Override
  public void run() {
    while (runProcess) {
      for (int i = 3; i > 0; i--) {
        message.setText(messageStr + " " + i + " Sec.");
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      runProcess = false;
    }
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == yes) {
    } else {
      dialog.dispose();
    }
  }

  public static void main(String args[]) {
    Main ean = new Main();
  }
}