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:

JFrame Test
JFrame Test

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.

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

JFrame - Main Frame Class

Creating Frames with Sizes and Locations

 Closing Frame and Terminating Application

 Listing and Interrupting AWT Threads

 "AWT blocker activation interrupted" Error in JDK 1.6

 JFrame Thread Behavior with JDK 8 to 20

 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

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials

 References

 Full Version in PDF/EPUB