0

I tried to center my dialog (i am using java 1.3) but it does not seem to work. i tried all below ways..

dialog.setSize(100, 100);
dialog.setResizable(true);

dialog.setLocation(150, 250);
dialog.setLocationRelativeTo(dialog.getParent());

the size of the dialog does not change when i change values in setSize method. The location does not change when i change values in setLocation method. It is very old code so i am not much sure what to do or how to get it workign..

Amar
  • 1,556
  • 3
  • 18
  • 28
  • Does your dialog have a parent? Is the parent visible? – icza Sep 11 '14 at 06:19
  • first you setting hardcode location and afterwards you setting it as relative to parent, it doesnt make sense. – smajlo Sep 11 '14 at 06:24
  • @icza i dont think it has a parent since it is created by `new IDialog(null, "title", true);` – Amar Sep 11 '14 at 06:30
  • @smajlo i tried both by commenting one at a time just to check... – Amar Sep 11 '14 at 06:31
  • 2
    Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This will result in less confusion and better responses – MadProgrammer Sep 11 '14 at 06:41
  • Probable duplicate of [Center `JDialog` over parent](http://stackoverflow.com/q/10030947/418556). – Andrew Thompson Sep 11 '14 at 07:46
  • 1
    I just realized you wrote you use Java 1.3. `setLocationRelativeTo()` was added in Java 1.4. If you don't get a compile error, you are not using Java 1.3. – icza Sep 11 '14 at 08:50

1 Answers1

1

First you should build the content of the dialog, and only bother sizing it and setting its location after that.

Best would be to use proper layout managers, and once you added all your components (content) to it, simply call its pack() method to have the layout managers compute the size.

After that you can simply center it by calling:

dialog.setLocationRelativeTo(null);

Passing null means to center it on the screen. Quoting from the javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.

Although if it has a parent, dialog.getParent() should be passed just as you did which also works if it has no parent (null).

icza
  • 389,944
  • 63
  • 907
  • 827