Using secondary loops to mimic modal dialog boxes - Java Swing

Java examples for Swing:JDialog

Introduction

A SecondaryLoop permits the execution of some task while blocking the current thread, until the secondary loop is complete.

Demo Code

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.SecondaryLoop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main extends JFrame implements ActionListener {

  private JButton firstButton;
  private JButton secondButton;

  public Main() {
    this.setTitle("Example");

    this.setBounds(100, 100, 200, 200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());

    firstButton = new JButton("First");
    this.add(firstButton);
    firstButton.addActionListener(this);

    secondButton = new JButton("Second");
    this.add(secondButton);
    secondButton.addActionListener(this);
  }/*from w w  w .  j av  a  2s .  com*/

  @Override
  public void actionPerformed(ActionEvent e) {
    Thread worker;
    JButton button = (JButton) e.getSource();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    EventQueue eventQueue = toolkit.getSystemEventQueue();
    SecondaryLoop secondaryLoop = eventQueue.createSecondaryLoop();

    Calendar calendar = Calendar.getInstance();
    String name;

    if (button == firstButton) {
      name = "First-" + calendar.get(Calendar.MILLISECOND);
    } else {
      name = "Second-" + calendar.get(Calendar.MILLISECOND);
    }
    worker = new WorkerThread(secondaryLoop, name);
    worker.start();

    if (!secondaryLoop.enter()) {
      System.out.println("Error with the secondary loop");
    } else {
      System.out.println(name + " Secondary loop returned");
    }
  }

  public static void main(String[] args) {

    SwingUtilities.invokeLater(() -> {
        Main window = new Main();
        window.setVisible(true);
    });

  }
}

class WorkerThread extends Thread {

  private String message;
  private SecondaryLoop secondaryLoop;

  public WorkerThread(SecondaryLoop secondaryLoop, String message) {
    this.secondaryLoop = secondaryLoop;
    this.message = message;
  }

  @Override
  public void run() {
    System.out.println(message + " Loop Sleeping ... ");
    try {
      Thread.sleep(2000);
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
    System.out.println(message + " Secondary loop completed with a result of " + secondaryLoop.exit());
  }
}

Related Tutorials