Java Swing Tutorial - JFrame








Let's start with the simplest Swing program.

We will use a JFrame, which is a top-level container, to create our first application. To create and display a JFrame, we need to do the following:

  • Create a JFrame object.
  • Make it visible.

To create a JFrame object, we can use the constructors of the JFrame class.

In the following code we use the constructor which takes a string. The string value will be displayed as the title for the JFrame.

Classes representing Swing components are in the javax.swing package, so is the JFrame class.

The following code creates a JFrame object with its title set to "Swing":

// Create a  JFrame  object
JFrame  frame  = new JFrame("Swing");




Show a JFrame

When we create a JFrame object, by default, it is not visible. We have to call its setVisible(boolean visible) method to make it visible. true parameter makes the frame visible, to hide the frame pass false to the setVisible method.

To Make the JFrame visible on the screen

frame.setVisible(true);

The following code wraps the two statements, to create and display a JFrame, into one statement.

new JFrame("Swing").setVisible(true);
import javax.swing.JFrame;
/*from   w  ww . jav  a2 s  . c  o  m*/
public class Main {
  public static void main(String[] args) {
    // Create a frame
    JFrame frame = new JFrame("Swing");
    // Display the frame
    frame.setVisible(true);
  }
}




Exit a Swing application

We can define one of the four behaviors of a JFrame to determine what happens when the JFrame is closed.

The constants are defined in the javax.swing.WindowsConstants interface.

The JFrame class implements the WindowsConstants interface. We can reference all these constants using JFrame.CONSTANT_NAME syntax or we can use the WindowsConstants.CONSTANT_NAME syntax.

The four constants are

  • DO_NOTHING_ON_CLOSE
    do not do anything when the user closes a JFrame.
  • HIDE_ON_CLOSE
    hides a JFrame when the user closes it. This is the default behavior. The JFrame is invisible but the program is still running.
  • DISPOSE_ON_CLOSE
    hides and disposes of the JFrame when the user closes it. Disposing a JFrame releases any resources used by it.
  • EXIT_ON_CLOSE
    exits the application. This option will exit the application.

We can set the default close behavior of a JFrame by passing one of the four constants to its setDefaultCloseOperation() method.

The following code shows how to exit the application when the JFrame is closed

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The above JFrame has no viewable area. It displays only the title bar.

JFrame Size

We need to set the size and position of your JFrame to show its content area.

The size of a frame is defined by its width and height in pixels and we can set them using setSize(int width, int height) method.

The position is defined by the (x, y) coordinates in pixels of the top-left corner of the JFrame with respect to the top-left corner of the screen.

By default, its position is set to (0, 0) and this is the reason the JFrame was displayed at the top-left corner of the screen.

We can set the (x, y) coordinates of the JFrame using its setLocation(int x, int y) method.

To set its size and position in one step, use its setBounds(int x, int y, int width, int height) method.

The following code gives size and sets position of the JFrame.

import javax.swing.JFrame;
/* ww  w . ja v a2s .  c o  m*/
public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Swing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set the x, y, width and height properties
    frame.setBounds(50, 50, 200, 200);

    frame.setVisible(true);
  }
}

Adding Components to a JFrame

To position a JFrame in the center of the screen, call its setLocationRelativeTo() method with a null argument.

When adding UI controls to JFrame, we add them to the content pane of JFrame.

The content pane from JFrame holds the Swing components of a JFrame.

To get the reference of the content pane from JFrame use the following code.

// Create a  JFrame
JFrame  frame  = new JFrame("Test");

// Get the reference of  the   content  pane
Container contentPane = frame.getContentPane();

After getting the reference for the content pane from JFrame we can add components by using the add() method.

// Add aComponent to contentPane 
contentPane.add(aComponent);

The following code adds a JButton to JFrame. An object of the JButton class represents a button, such as an OK button on a message box.

A JButton contains label text. The next line uses the Close as JButton's label text.

// Create a  JButton with  Close  text
JButton closeButton  = new JButton("Close");

To add closeButton to the content pane of a JFrame, we have to do two things:

Get the reference of the content pane of the JFrame.

Container contentPane = frame.getContentPane();

Call the add() method of the content pane.

contentPane.add(closeButton);

To add a JButton to JFrame using one line of code, combine all statements into one.

frame.getContentPane().add(new JButton("Close"));

The full source code.

import java.awt.Container;
//from  ww  w. j  a  va2 s .c  o  m
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Add a close button
    JButton closeButton = new JButton("Close");
    contentPane.add(closeButton);

    // set the size of the frame 300 x 200
    frame.setBounds(50, 50, 300, 200);
    frame.setVisible(true);
  }
}

Pack JFrame

The pack() method of the JFrame examines all the components on the JFrame and decides their preferred size and sets the size of the JFrame just enough to display all the components.

When we call pack() method, we do not need to set the size of the JFrame. The pack() method will calculate the size of the JFrame and set it.

When using the pack() method, we don't need to call the setBounds() method.

To position a JFrame after pack() method, use setLocation(x, y) method.

import java.awt.Container;
//  w  ww  .  j a v a 2 s  .co m
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Add a close button
    JButton closeButton = new JButton("Close");
    Container contentPane = frame.getContentPane();
    contentPane.add(closeButton);

    // Calculates and sets appropriate size for the frame
    frame.pack();

    frame.setVisible(true);
  }
}

JFrame State

We can set the state of a JFrame programmatically using the setExtendedState(int state) method.

The state is specified using constants defined in the java.awt.Frame class from which the JFrame class is inherited.

To display the JFrame maximized

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

The following table lists Constants That Define States of a JFrame

JFrame State
Constants
Description
NORMALJFrame is displayed in normal size.
ICONIFIEDJFrame is displayed in minimized state.
MAXIMIZED_HORIZJFrame is displayed maximized horizontally, but in normal size vertically.
MAXIMIZED_VERTJFrame is displayed maximized vertically, but in normal size horizontally.
MAXIMIZED_BOTHJFrame is displayed maximized horizontally as well as vertically.

Default Button

Sometimes we may want to use a default button in your JFrame or JDialog. A default button is an instance of the JButton class, which is activated when the user presses a key on the keyboard.

A key that activates the default button is defined by the look-and-feel.

Typically, the key to activate the default button is the Enter key.

We can set a default button for a JRootPane, which is present in a JFrame, JDialog, JWindow, JApplet, and JInternalFrame.

Usually, we set the OK button as a default button on a JDialog. If a JRootPane has a default button set, pressing the Enter key will activate that button.

// Create a  JButton
JButton okButton   = new JButton("OK");
// Set  okButton   as  the   default  button 
frame.getRootPane().setDefaultButton(okButton);

Window Event

We can add a window listener to a JFrame or any other top-level Swing window that will notify changes in a window's state.

The following code adds a window listener to a JFrame named frame.

If we are interested in listening for only few window state changes, we can use the WindowAdapter class instead of the WindowListener interface.

The WindowAdapter class provides an empty implementation of all the seven methods in the WindowListener interface.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
//ww  w .  j  a  v a  2s.  c  o  m
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) throws IOException {
    JFrame frame = new JFrame();
    frame.addWindowListener(new WindowListener() {
      @Override
      public void windowOpened(WindowEvent e) {
        System.out.println("JFrame has  been  made visible first  time");
      }

      @Override
      public void windowClosing(WindowEvent e) {
        System.out.println("JFrame is closing.");
      }

      @Override
      public void windowClosed(WindowEvent e) {
        System.out.println("JFrame is closed.");
      }

      @Override
      public void windowIconified(WindowEvent e) {
        System.out.println("JFrame is  minimized.");
      }

      @Override
      public void windowDeiconified(WindowEvent e) {
        System.out.println("JFrame is restored.");
      }

      @Override
      public void windowActivated(WindowEvent e) {
        System.out.println("JFrame is activated.");
      }

      @Override
      public void windowDeactivated(WindowEvent e) {
        System.out.println("JFrame is deactivated.");
      }
    });

    // Use the WindowAdapter class to intercept only the window closing event
    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        System.out.println("JFrame is closing.");
      }
    });

  }
}

We are done with a window (JFrame, JDialog or JWindow), we should call its dispose() method.

dispose() method makes a window invisible and release the resources to the operating system.