Set location of JDialog relative to JFrame

后端 未结 3 2015
旧时难觅i
旧时难觅i 2021-02-04 13:38

Is there a way to set a dialog location relative to a JFrame?

I would like to center the dialog to the frame that houses my GUI, instead the dialog often a

3条回答
  •  抹茶落季
    2021-02-04 14:01

    The method you want is: setLocationRelativeTo()

    Adding it with null to the JFrame, will center it on the screen. Adding the JFrame to the dialog will center it on the jframe.

    Cheers.

    import javax.swing.JDialog;
    import javax.swing.JFrame;
    
    public class Centered
    {
        public static void main( String args[] )
        {
            JFrame jFrame = new JFrame();
    
            jFrame.setSize( 250 , 250 );
            jFrame.setLocationRelativeTo( null );
            jFrame.setVisible( true );
    
            JDialog jDialog = new JDialog();
            jDialog.setLocationRelativeTo( jFrame );
            jDialog.setVisible( true );
        }
    }
    

提交回复
热议问题