Showing posts with label java swing frame. Show all posts
Showing posts with label java swing frame. Show all posts

Tuesday, May 24, 2011

Positioning a Frame

In the previous chapter, we learnt how to create a simple frame. Now, let us take a look at how we can position the frame in the screen.

So, lets get started!!!

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
setLocationByPlatform(true);

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

Note:
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);
setLocationByPlatform(true);

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
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
• 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?

Code:

import java.awt.*;
import javax.swing.*;

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
public class MyTestSizedFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
FirstSizedFrame frame = new FirstSizedFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

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);
setLocationByPlatform(true);

// set frame title
setTitle("TestSizedFrame");
}
}

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

If you run this code you will get an output like below:



Prev: Creating a Frame

Next: Displaying Text in a Component

Creating a Frame

Now that we know the history of Java Swings, lets get down to business. The first thing we are going to learn is “How to create a Frame”

So, lets get started!!

What is Frame?

A top-level window (i.e., a window that is not contained inside another window) is called a frame in Java. The AWT library has a class, called Frame, for this top level. The Swing version of this class is called JFrame and extends the Frame class. The JFrame is one of the few Swing components that is not painted on a canvas. Thus, the decorations (buttons, title bar, icons, and so on) are drawn by the user’s windowing system, not by Swing.

Trivia:
Most Swing component classes start with a “J”: JButton, JFrame, and so on. There are classes such as Button and Frame, but they are AWT components. If you accidentally omit a “J”, your program may still compile and run, but the mixture of Swing and AWT components can lead to visual and behavioural inconsistencies.

How would a Frame Look?

An empty or a simple frame will look like below:


Don't lose heart. This frame practically has no components in it. It is just a simple window that we have created with no components or fields in it.

What is the code to generate this Frame?


The code is pretty straight forward and is available below:
import java.awt.*;
import javax.swing.*;

/**
* @version 1.0 24-May-2011
* @author Anand Vijayakumar
*/
public class MyFirstFrame
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
FirstFrame frame = new FirstFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class FirstFrame extends JFrame
{
public FirstFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}


If you are new to swings, don't lose heart just yet. I am not going to leave you all by yourself to figure this out. Lets go through this code line by line.

The first lines are the import statements. The Swing classes are placed in the javax.swing package. The package name javax indicates a Java extension package, not a core package. For historical reasons, Swing is considered an extension. However, it is present in every Java SE implementation since version 1.2.

By default, a frame has a rather useless size of 0 × 0 pixels. We define a subclass FirstFrame whose constructor sets the size to 300 × 200 pixels. This is the only difference between a FirstFrame and a JFrame. (We have set a size instead of 0 X 0)

In the main method of the Test class, we construct a FirstFrame object and make it visible.
There are two technical issues that we need to address in every Swing program.

First of all Swing components must be configured from the event dispatch thread, the thread of control that passes events such as mouse clicks and keystrokes to the user interface components. The following code fragment is used to execute statements in the event dispatch thread:
EventQueue.invokeLater(new Runnable()
{
public void run()
{
statements
}
});

I know that, this is too much to swallow in one bite, but stay with me here. For now just think of this as a magic wand that is used to start your Swing program. We will get into the details in the subsequent chapters.

Next, we define what should happen when the user closes the application’s frame. Since this is our first simple example, we just want to exit when the user clicks the close icon ‘X’. To make this happen, we use the statement

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

In other programs with multiple frames, you would not want the program to exit just because the user closes one of the frames. By default, a frame is hidden when the user closes it, but the program does not terminate.

Trivia:
I know that it is kind of surprising that the program doesn't terminate when the user clicks the close icon. Unfortunately that is how Swing works and we have to manually write the code to exit.

Simply constructing a frame does not automatically display it. Frames start their life invisible. That gives the programmer the chance to add components into the frame before showing it for the first time. To show the frame, the main method calls the setVisible method of the frame.

After scheduling the initialization statements, the main method exits.

Did you notice something Surprising?

If you havent yet run the code I pasted above, I suggest you do it in order to be surprised.
Did you see that, even though the code in the main method has completed execution, the frame is still visible? This is unlike regular java programs that exit once the main method is done executing.

The reason is that, the event dispatch thread keeps the program alive until it is terminated, either by closing the frame or by calling the System.exit method.

Prev: Introduction to Java Swings

Next: Positioning a Frame
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers