Java Swing How to - Create a modal JDialog on top of another modal JDialog








Question

We would like to know how to create a modal JDialog on top of another modal JDialog.

Answer

import java.awt.BorderLayout;
import java.awt.Window;
/*from ww  w  . j a va  2s. co m*/
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Main {
  public static JPanel newPane(String labelText) {
    JPanel pane = new JPanel(new BorderLayout());
    pane.add(newLabel(labelText));
    pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
    return pane;
  }

  private static JButton newButton(String label) {
    final JButton button = new JButton(label);
    button.addActionListener(e -> {
      Window parentWindow = SwingUtilities.windowForComponent(button);
      JDialog dialog = new JDialog(parentWindow);
      dialog.setLocationRelativeTo(button);
      dialog.setModal(true);
      dialog.add(newPane("Label"));
      dialog.pack();
      dialog.setVisible(true);
    });
    return button;
  }

  private static JLabel newLabel(String label) {
    JLabel l = new JLabel(label);
    return l;
  }

  public static void main(String[] args) {
    JPanel pane = newPane("Label in frame");
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(pane);
    frame.pack();
    frame.setVisible(true);
  }
}