• home
  • forum
  • my
  • kt
  • download
  • Center a Dialog Box, Frame or Window in Java

    Author: 2007-08-03 13:06:10 From:

    Are you tired of the random location of the windows in your application? It is time to take control of your window's position. This tutorial looks at how to center a dialog box, frame, or window in Java.

    Java 1.4 or newer
    If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

    Java 1.3 or older
    We can query the toolkit to determine the size of the screen. The getScreenSize() method will return a Dimension object which contains the width and height.

    //Get the screen size
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();

    Once you have the screen width and height, you can simply subtract the window width and height from the screen width and height and divide it in half.

    //Create a new JFrame
    JFrame frame = new JFrame("Demo");
    frame.setSize(400, 600);
    
    //Calculate the frame location
    int x = (screenSize.width - frame.getWidth()) / 2;
    int y = (screenSize.height - frame.getHeight()) / 2;
    
    //Set the new frame location
    frame.setLocation(x, y);

    In our example above, we centered a JFrame, but the same code will work for a dialog box or a window.

    Let's extend our example to create a dialog box class that will automatically center itself. Our CenterDialogBox class will extend a JDialog and over-ride the setSize() method. The dialog box will center itself after the setSize() method has been called.

    //Create a new JFrame
    public class CenterDialogBox extends JDialog
    {
    	public void setSize(int width, int height)
    	{
    		super.setSize(width, height);
    		
    		//Get the screen size
    		Toolkit toolkit = Toolkit.getDefaultToolkit();
    		Dimension screenSize = toolkit.getScreenSize();
    
    		//Calculate the frame location
    		int x = (screenSize.width - getWidth()) / 2;
    		int y = (screenSize.height - getHeight()) / 2;
    		
    		//Set the new frame location
    		setLocation(x, y);				
    	}
    	
    	public void setSize(Dimension size)
    	{
    		setSize(size.width, size.height);
    	}	
    }

    You can also use this to create your own class that can create a self-centering JWindow or JFrame.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Applet Building (2)
      Application Building (3)
      Communication (1)
      Database Related (8)
      Development (12)
      EJB (14)
      Game Programming (2)
      General Java (38)
      Javabeans (4)
      JSP and Servlets (8)
      Miscellaneous (23)
      Networking (1)
      Security (2)
      Swing (13)
      WAP and WML (1)
      XML and Java (0)

    New

    Hot