Monday, July 6, 2009

Centering Java Windows & Dialogs

Centering Windows:
Thought I would share a quick little trick for those who haven't already found this out. Many times when you display an Application window or Dialog box you want it to appear centered either onscreen or centered within another window or component. Instead of figuring out the absolute position of the window or dialog on screen there is a much easier solution.
JFrame mainFrame = new JFrame("Test Center On Screen");
//must have this in order to porperly exit application when window closes

//size must be set prior to setting location.
mainFrame.setSize(600, 400);

//this is on way to center the frame

//show the window.
Alternatives to setting the size with absolute values is using the pack(); function which will use the preffered size and layout managers to determine the window size.

Another way to center the frame is by calling the same setLocationRelativeTo(); function as follows.
//same as above
There is no advantage to using either method, as far as I know, so it's whichever you believe makes the most sense to read.

Centering Dialogs:
Similarily you can center Dialogs or even Windows on any component. This is useful for modal dialogs that need to be closed before the user can continue working in the main application.

//create a new modal dialog
JDialog dlg = new JDialog(mainFrame, true);

//simply dispose of the dialog

//set the size prior to setting location
dlg.setSize(300, 200);

//center the dialog in the application window

//display the modal dialog
So as you can see it's quite simple to center windows and dialogs in Java. You can also center a Dialog or Window to any Component using the same setLocationRelativeTo function thus when setVisible(true); is called the Window will appear centered over that component on screen.