Return to Programming Languages

Frames

Contents

  1. Introduction
  2. Creating a Frame
  3. Making Frames Visible
  4. Giving the Frame a Title
  5. Ending your Frame Program Properly
  6. Positioning your Frame
  7. Adding Components to your Frame
  8. References
  9. Copyright

1. Introduction

A frame, or "window", is a container that holds other Swing components. Components include your buttons, text fields, text areas, combo boxes, radio buttons, checkboxes and many others. The frame is the basic foundation for creating your graphical user interface.

If you’ve ever done any web design, you can think of a frame as the webpage, and the components are all the buttons, radio buttons, checkboxes and jump menus you see on the page. This isn’t a very accurate analogy, but just keep in mind one thing: a frame is what you put your components into. (Note that frames here have nothing to do with the frames used to separate webpages.)

2. Creating a Frame

To create a frame object, we need to use the JFrame class. JFrame is part of the Swing classes, so we have to import javax.swing.*;. The following program creates a frame by creating an instance of the JFrame class. The instance variable is given the name myFrame.

import javax.swing.*;  // import Swing classes

public class FramesFun {
 public static void main(String[] args)
 {
   JFrame myFrame = new JFrame();    // create a new instance of JFrame called myFrame
 }
}

Simple enough, right? However, if you try compiling and running the program, you won’t see anything. This is because although you have created a frame object, you haven’t yet made it visible. By default, frames are invisible until you make them otherwise. Let’s revise our code then.

3. Making Frames Visible

import javax.swing.*;   // import Swing classes

public class FramesFun()
{
  JFrame myFrame = new JFrame();    // create a new frame
  myFrame.setSize(300,300);         // specify the width and height of the frame
  myFrame.setVisible(true);         // make the frame visible
}

Note that the we have called two methods using our myFrame object: setSize and setVisible.

The setSize method simply specifies the dimensions of the frame. The first argument is the width of the frame, the second argument is the height of the frame. Both are measured in pixels.

The setVisible method is the one that makes the frame visible. Note that if we passed in false instead of true, the frame won’t appear. But why would anybody want to pass in false, you ask? Well, sometimes in GUI programming, you may find that a certain window isn’t needed temporarily, so you make it invisible.

Now compile and run your program again. This time your frame should resemble the frame in the following picture. Note that this picture shows a frame when the program was run on Windows XP. On other versions of Windows and other operating systems, your frame will look different.

A Frame

It would be wise now to mention that there are two alternatives to setSize and setVisible for a JFrame object. They are:

4. Giving the Frame a Title

Although we now have a visible frame, it looks kind of plain. Let's spruce things up by giving our frame a title. To do this, we just have to use the setTitle method:
import javax.swing.*;

public class FramesFun {

  public static void main(String[] args)
  {
    JFrame myFrame = new JFrame();
    myFrame.setTitle("My First Frame!");	// set the title of the frame
    myFrame.setSize(300,300);
    myFrame.setVisible(true);
  }
}

And the next picture shows the result of using the setTitle method. The title bar now contains the words "My First Frame!".

Frame with a title

In fact, you need not use the setTitle method at all. The JFrame class has a constructor that takes in a String argument that represents the title. The following program code will produce a similar frame as the previous program.

import javax.swing.*;

public class FramesFun {

  public static void main(String[] args)
  {
    JFrame myFrame = new JFrame("My First Frame!");	// set title using JFrame constructor
    myFrame.setSize(300,300);
    myFrame.setVisible(true);
  }
}

5. Ending your Program Properly

You may not have noticed it, but so far all our frame programs have a little problem. When you close the frame, the program does not terminate. All we have done is actually hide the frame. To solve this problem, we introduce one more method: setDefaultCloseOperation. Study the following program:

import javax.swing.*;

public class FramesFun {

  public static void main(String[] args)
  {
    JFrame myFrame = new JFrame();
    myFrame.setTitle("My First Frame!");	
    myFrame.setSize(300,300);
    myFrame.setVisible(true);
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	// terminates program when frame is closed
  }
}

For now, just accept and memorise that setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) termiantes your frame program properly. The method specifies what will happen when you decide to close a frame. Other possible values besides EXIT_ON_CLOSE include:

6. Positioning your Frame

Any frame you create is by default displayed in the upper-left corner of your screen. Use the setLocation(x,y) method in the JFrame class to set the location of your upper-left corner of your frame at (x,y). Where this corner is placed will affect where your whole frame is displayed.

What if you want to center your frame relative to the screen? This is harder than it seems, because different computers have different screen widths and resolutions. Fortunately, we can use the Toolkit and Dimension classes. Both are found in the java.awt package.

The Dimension class encapsulates the width and height of a component (in integer precision) in a single object. This component can be the computer screen, a frame or a UI component. The Dimension class has two useful public properties width and height

The Toolkit class contains many useful methods that are concerned with platform-specific services such as printing, fonts, images, and display parameters. One of the methods it has is getScreenSize(), which returns the screen size as a Dimension object.

Although the Toolkit is used frequently, both directly and behind the scenes, you would never create any of these objects directly. When you need a Toolkit, you ask for it with the static method getDefaultToolkit() or the Component.getToolkit() method.

So if I wanted to find out the screen width and height, I would use the following code

 // obtain the screen size of the user's computer as a Dimension object
 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 

 // Obtain the width and height of the screen
 int screenWidth = screenSize.width;
 int screenHeight = screenSize.height;

Now, let us center our frame with the following code:

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

 public class CenterFrame {

   public static void main(String[] args) {

     JFrame myFrame = new JFrame();
     myFrame.setSize(300,200);
     myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     // Obtain the dimensions of the screen
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
     int screenWidth = screenSize.width;
     int screenHeight = screenSize.height; 

     // obtain the dimension of our frame
     Dimension myFrameSize = myFrame.getSize();
     int x = ( screenWidth - myFrameSize.width )/2;
     int y = ( screenHeight - myFrameSize.height )/2; 

     myFrame.setLocation(x,y);
     myFrame.setVisible(true);
   }
  }

7. Adding Components to your Frame

So far, we've covered a lot of frame stuff, but not how to add components to our frames. This last section will cover that.

Every frame object has a content pane. This content pane is where you put all your components, your content, in. The following code gets our frame's contain pane.

   myFrame.getContentPane();

After we have the content pane, we add components using the add() method. The following code adds a JButton component into our frame's content pane.

   myFrame.getContentPane().add( new JButton("Click me!");

The source code below will make a frame with a button added inside.

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

 public class FrameWithButton { 

  public static void main(String[] args)
  {
    JFrame myFrame = new JFrame("A Frame with a Button");
    myFrame.getContentPane().add(new JButton("Click me!"));    // add a button with label "Click Me!"
    myFrame.setSize(300,200);
    myFrame.show();
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
 }

This picture shows what I got on my University's school computer that runs Windows 2000.

Frame with a button

Note that the JButton component takes up the whole frame no matter how you resize the window. In a future, we'll discuss Layout Managers that will help us position components within frames better.

8. References

Author: Dante Shamest.
Copyright © 2002 Dante Shamest
This tutorial was last modified 16th November 2002