javaswingjframejdialog

How to get a JFrame position in the screen to put in a JDialog?


i was wondering if it possible to get the position of the location on the screen of a JFrame, to put the same location in a JDialog. I mean, that i want to do is when i open a JDialog from a JFrame button, i want to put the JDialog in the same position that the main JFrame, maybe with the .setLocationRelativeto() method, any ideas to do it??, thank you!.

   this.setUndecorated(true);
   initComponents();
   this.setBounds(WIDTH, WIDTH, 444, 308);
   JDialog dialog=new JDialog();

I want to adopt the same position from the mainJFrame, but i dont know how to to it....

   dialog.setLocationRelativeTo();  

Solution

  • is it possible to get the position of the location on the screen of a JFrame

    The code in the ActionListener would be something like:

    Component c = (Component)event.getSource();
    Window window = SwingUtilities.windowForComponent(c);
    JDialog dialog = new JDialog(...);
    ...
    dialog.pack();
    dialog.setLocation( window.getLocation() );
    dialog.setVisible( rue ;
    

    or you could center the dialog on the frame by using:

    dialog.setLocationRelativeTo( window );
    dialog.setVisible( true );
    

    EDIT For the record, JFrame extends Window, so if you already have your JFrame, that may be enough.