Java Swing How to - Set the location of a JOptionPane according to its parent frame








Question

We would like to know how to set the location of a JOptionPane according to its parent frame.

Answer

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/*from  ww w  .  j  a  v a 2s .c  o  m*/
public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Button");
    frame.add(button);

    frame.setAlwaysOnTop(true);
    frame.setSize(500, 500);
    frame.setLocation(500, 500);

    button.addActionListener(e->{
        JOptionPane optionPane = new JOptionPane("Option Pane");
        optionPane.showMessageDialog(frame, "Message!"); 
    });

    frame.setVisible(true);
  }
}