Java Frame Desktop Position


By default the frame, you create, is placed on the left top corner of the monitor by JVM. But you can dictate the position. In the following program, the frame is positioned in the center of the monitor. The task here is, you must get the screen (monitor) size and your frame size dynamically throuh the program. Once you get these, with setLocation() method, the fame can be positioned on the display screen where you would like.

Example on Java Frame Desktop Position

The following program positions the frame in the center of the monitor.

import java.awt.*;
public class FP extends Frame
{
  public FP()
  {                                  // create a frame of your own size
    setSize(300, 350);
    setVisible(true);
		                     // obtain the screen (monitor) size
    Toolkit tk = Toolkit.getDefaultToolkit();
		                     // get your frame size                                      
    Dimension screenSize = tk.getScreenSize();
                                     
     Dimension frameSize = getSize();
		                     // get the center point width-wise                                    
     int w = (screenSize.width - frameSize.width)/2;
                                     // get the center point height-wise
     int h = (screenSize.height - frameSize.height)/2;
                                     // place the frame
     setLocation(w, h);
  }
  public static void main(String args[])
  {
    new FP();
  }
}

Earlier, we used Toolkit class to know the font list supported by Java. The same java.awt.Toolkit is used here to get the monitor size in pixels. The getScreenSize() method of Toolkit returns a java.awt.Dimension object that embeds the width and height of the monitor. The getSize() method of Frame class (inherited from its super class java.awt.Component) returns the size of the frame as a Demension object. width and heght are the variables of Dimension class that returns the width and height of the component.

Dimension frameSize = getSize();

The above statement can be replaced with the following.

Rectangle frameSize = getBounds();

2 thoughts on “Java Frame Desktop Position”

  1. sir!!!by compling above program it is displaying a error “screensize variable not found”.so could you help???

Leave a Comment

Your email address will not be published.