Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

Creating Frames with Sizes and Locations

This section provides a tutorial example on how to create a frame with a given size and a given location with setBounds() and setVisible() methods.

Problem: I want to create a frame window with a specific size and display it on the screen at a specific location.

Solution: You can use the JFrame.setBounds() method define the frame location and size. Then use the setVisible() method to make the frame visible on the screen. The following sample code, JFrameTest.java, shows you how to do this.

import javax.swing.*;
public class JFrameTest {
   public static void main(String[] a) {
      JFrame f = new JFrame("Frame Title");
      f.setBounds(50,50,150,150);
      f.setVisible(true);
   }
}

If you run this example, you will get:
Using paint() on Frame

Note 1: The size specified in the setBounds() method includes both the content area and the title area of the frame.

Note 2: After executing the f.setVisible(true) statement, the main() method reaches the end of execution. But the execution of the entire program is not terminated. This is due the fact that the f.setVisible(true) statement actually launches new execution threads, AWT threads. Those threads are still running even after the main thread reaches the end.

Note 3: When you click the close icon, the frame will be removed from the screen. But the execution of the entire program is not terminated. Removing all frames from the screen does not force all AWT threads to end.

Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.1, 1.5.0, and 1.6.0.

Last update: 2009.

Sections in This Chapter

Creating Frames with Sizes and Locations

Closing Frame and Terminating Application

Listing and Interrupting AWT Threads

"AWT blocker activation interrupted" Error

Displaying Chinese Characters in Frame Title

Drawing Graphics - Using paint() on Frame

Drawing Graphics - Using paint() on Component

Drawing Graphics - Using paint() on Content Pane

Drawing Chinese Characters on Frames

Dr. Herong Yang, updated in 2009
Creating Frames with Sizes and Locations