Java Swing How to - Set JDialog relative to a button








Question

We would like to know how to set JDialog relative to a button.

Answer

import java.awt.Window;
//from   ww  w. j a v  a2 s  .  co  m
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame(Main.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JButton button = new JButton("Click me to open dialog");
    button.addActionListener(e -> {
      Window parentWindow = SwingUtilities.windowForComponent(button);
      JDialog dialog = new JDialog(parentWindow);
      dialog.setLocationRelativeTo(button);
      dialog.setModal(true);
      dialog.add(new JLabel("A dialog"));
      dialog.pack();
      dialog.setVisible(true);
    });
    frame.add(button);
    frame.pack();
    frame.setVisible(true);
  }
}