Java Swing How to - Open new JDialog in JDialog








Question

We would like to know how to open new JDialog in JDialog.

Answer

import java.awt.Dialog;
import java.awt.event.ActionEvent;
/*  w w  w .j av  a 2 s . c  o m*/
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class Main {
  private static int index;

  static class OpenAction extends AbstractAction {

    public OpenAction() {
      super("Open");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
      JDialog jd = new JDialog();
      jd.setTitle("D" + String.valueOf(++index));
      jd.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
      jd.add(new JButton(new OpenAction()));
      jd.pack();
      jd.setLocationRelativeTo(null);
      jd.setVisible(true);
    }
  }

  private void display() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new JButton(new OpenAction()));
    f.pack();
    f.setVisible(true);
  }

  public static void main(String[] args) {

    new Main().display();

  }
}