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");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.
//must have this in order to porperly exit application when window closes
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//size must be set prior to setting location.
mainFrame.setSize(600, 400);
//this is on way to center the frame
mainFrame.setLocationRelativeTo(null);
//show the window.
mainFrame.setVisible(true);
Another way to center the frame is by calling the same setLocationRelativeTo(); function as follows.
//same as aboveThere is no advantage to using either method, as far as I know, so it's whichever you believe makes the most sense to read.
mainFrame.setLocationRelativeTo(mainFrame);
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.
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.
//create a new modal dialog
JDialog dlg = new JDialog(mainFrame, true);
//simply dispose of the dialog
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
//set the size prior to setting location
dlg.setSize(300, 200);
//center the dialog in the application window
dlg.setLocationRelativeTo(mainFrame);
//display the modal dialog
dlg.setVisible(true);
No comments:
Post a Comment