Friday, June 24, 2011

Swing : Positioning a Frame

The JFrame class itself has only a few methods for changing how frames look. Of course, through the magic of inheritance, most of the methods for working with the size and position of a frame come from the various superclasses of JFrame.

The most important methods related to positioning a Frame are:
• The setLocation and setBounds methods for setting the position of the frame
• The setIconImage method, which tells the windowing system which icon to display in the title bar, task switcher window etc
• The setTitle method for changing the text in the title bar
• The setResizable method, which takes a boolean to determine if a frame will be resizeable by the user

Inheritance Hierarchy of the Frame

In the previous paragraph, I said that because of the inheritance hierarchy of the JFrame class, many of the features of its parent classes are available to it. Before we get any further, if you have any doubts reg. the Java Inheritance concepts, Click Here and refresh your understanding of Inheritance.

The image below explains the inheritance hierarchy of the JFrame and the JPanel classes.

 The Component class (which is the ancestor of all GUI objects) and the Window class (which is the superclass of the Frame class) are the classes that you need to look to find the methods to resize and reshape frames. For example, the setLocation method in the Component class is one way to reposition a component.

setLocation(x, y)

The top-left corner is located x pixels across and y pixels down, where (0, 0) is the top-left corner of the screen.

Similarly, the setBounds method in Component lets you resize and relocate a component in one step.

setBounds(x, y, width, height)

Alternatively, you can give the windowing system control on window placement. If you call

Before displaying the window, the windowing system picks the location (but not the size), typically with a slight offset from the last window.

For a frame, the coordinates of the setLocation and setBounds are taken relative to the whole screen. As you will see in the future chapters, for other components inside a container, the measurements are taken relative to the container

Frame Properties

Many methods of component classes come in getter/setter pairs, such as the following methods of the Frame class:

public String getTitle()
public void setTitle(String title)

Such a getter/setter pair is called a property. A property has a name and a type. The name is obtained by changing the first letter after the get or set to lowercase. For example, the Frame class has a property with name title and type String.

Conceptually, title is a property of the frame. When we set the property, we expect that the title changes on the user’s screen. When we get the property, we expect that we get back the value that we set.

Practically speaking, we do not care how the Frame class implements this property. Perhaps it simply uses its peer frame to store the title. Perhaps it has an instance field

private String title;

Nonetheless, we are only bothered as to whether the value we set is displayed fine and the value we get is what is displayed on screen.

There is one exception to this get/set convention. For properties of type boolean, the getter starts with is. For example, the following two methods define the locationByPlatform property:

public boolean isLocationByPlatform()
public void setLocationByPlatform(boolean b)

Determining a Good Frame Size

If you don’t explicitly set the size for a frame, all frames will default to being 0 by 0 pixels. To keep our example programs simple, we resize the frames to a size that we hope works acceptably on most displays. However, in a professional application, you should check the resolution of the user’s screen and write code that resizes the frames accordingly. A window that looks nice on a laptop screen will look like a postage stamp on a high-resolution large desktop monitor.

To find out the screen size, use the following steps:

1. Call the static getDefaultToolkit method of the Toolkit class to get the Toolkit object. (The Toolkit class is a dumping ground for a variety of methods that interface with the native windowing system.)

2. Then call the getScreenSize method, which returns the screen size as a Dimension object. A Dimension object simultaneously stores a width and a height, in public (!) instance variables width and height.

This is a sample code:
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;

3. We use 50% of these values for the frame size, and tell the windowing system to position the frame as follows:

setSize(screenWidth / 2, screenHeight / 2);

Additional Tips for dealing with Frames:

Even though we have covered a lot of details about using frames, there are few more tips that will help you deal with these Frames properly.

  • If your frame contains only standard components such as buttons and text fields, you can simply call the pack method to set the frame size. The frame will be set to the smallest size that can accomodate all components. It is quite common to set the main frame of a program to the maximum size. As of Java SE 1.4, you can simply maximize a frame by calling
  • It is also a good idea to remember how the user positions and sizes the frame of your application and restore those bounds when you start the application again. We will learn how to do this in future.
  • If you write an application that takes advantage of multiple display screens, use the GraphicsEnvironment and GraphicsDevice classes to find the dimensions of the display screens. This will help us position and size our frames to look fine irrespective of the monitor size of your user
  • The GraphicsDevice class also lets you execute your application in full-screen mode.

Sample Code:

Our chapter wouldn't be complete without a code example, or would it?

public class MyTestSizedFrame
    public static void main(String[] args)
        EventQueue.invokeLater(new Runnable()
            public void run()
                FirstSizedFrame frame = new FirstSizedFrame();

class FirstSizedFrame extends JFrame
    public FirstSizedFrame()
        // get screen dimensions
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        int screenHeight = screenSize.height;
        int screenWidth = screenSize.width;

        // set frame width, height and let platform pick screen location
        setSize(screenWidth / 2, screenHeight / 2);

        // set frame title

The above is similar to the example in the previous chapter with the following differences:
  1. We have let the frame size to be determined based on the monitor screen size and height
  2. We have set a frame title

No comments:

Post a Comment