Java JFrame Example

In this article, we include a Java JFrame tutorial through examples. We will discuss some of the main methods and how JFrame and other main classes like JPanel, JLabel, and JButton fit into the Swing hierarchy. We will then create a simple GUI using the javax.swing package.

1. Introduction

JFC (Java foundation classes) encompasses a group of features for building graphical user interfaces (GUI) and adding rich graphics functionality and interactivity to Java applications. It contains: Swing GUI components (includes everything from buttons to split panes to tables), pluggable look and feel support, accessibility API, Java 2D API, and internationalization.

A frame (part of Swing GUI component), implemented as an instance of JFrame, is a window that has decorations such as a border, a title, and supports button components that close or iconify the window.

2. Swing hierarchy

The swing API has 18 public packages. Most programs majorly use javax.swing package. Let us look at the Swing hierarchy concentrating mainly on JFrame, JPanel, JButton and JLabel.

Java JFrame - Swing hierarchy to highlight JFrame, JPanel, JLabel and JButton
Fig 1. Swing hierarchy to highlight JFrame, JPanel, JLabel and JButton

3. JFrame

JFrame is an extended version of java.awt.Frame that adds support for JFC/ Swing component architecture. Like all other JFC/ Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. Let us look at the methods available in JFrame

Java JFrame - JFrame UML class diagram
Fig 2. JFrame UML class diagram

Let us now look at these methods and descriptions. Refer Java docs for more details. We will use some of these methods in our example.

  • protected void addImpl(Component comp, Object constraints, int index) : Adds the specified child Component. This method is overridden to conditionally forward calls to the contentPane. By default, children are added to the contentPane instead of the frame
  • protected JRootPane createRootPane() : Called by the constructor methods to create the default rootPane.
  • protected void frameInit() : Called by the constructors to init the JFrame properly.
  • public AccessibleContext getAccessibleContext() : Gets the AccessibleContext associated with this JFrame. For JFrames, the AccessibleContext takes the form of an AccessibleJFrame. A new AccessibleJFrame instance is created if necessary.
  • public Container getContentPane() : Returns the contentPane object for this frame.
  • public int getDefaultCloseOperation() : Returns the operation that occurs when the user initiates a “close” on this frame.
  • public Component getGlassPane() : Returns the glassPane object for this frame.
  • public Graphics getGraphics() : Creates a graphics context for this component. This method will return null if this component is currently not displayable.
  • public JMenuBar getJMenuBar() : Returns the menubar set on this frame.
  • public JLayeredPane getLayeredPane() : Returns the layeredPane object for this frame.
  • public JRootPane getRootPane() : Returns the rootPane object for this frame.
  • public TransferHandler getTransferHandler() : Gets the transferHandler property.
  • public static boolean isDefaultLookAndFeelDecorated() : Returns true if newly created JFrames should have their Window decorations provided by the current look and feel.
  • protected boolean isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are forwarded to the contentPane.
  • protected String paramString() : Returns a string representation of this JFrame. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations.
  • protected void processWindowEvent(WindowEvent e) : Processes window events occurring on this component. Hides the window or disposes of it, as specified by the setting of the defaultCloseOperation property.
  • public void remove(Component comp) : Removes the specified component from the container. If comp is not the rootPane, this will forward the call to the contentPane. This will do nothing if comp is not a child of the JFrame or contentPane.
  • public void repaint(long time, int x, int y, int width, int height) : Repaints the specified rectangle of this component within time milliseconds.
  • public void setContentPane(Container contentPane) : Sets the contentPane property. This method is called by the constructor.
  • public void setDefaultCloseOperation(int operation) : Sets the operation that will happen by default when the user initiates a “close” on this frame. Choices available are – DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE and EXIT_ON_CLOSE. The value is set to HIDE_ON_CLOSE by default.
  • public static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated) : Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window) provided by the current look and feel.
  • public void setGlassPane(Component glassPane) : Sets the glassPane property. This method is called by the constructor.
  • public void setIconImage(Image image) : Sets the image to be displayed as the icon for this window.
  • public void setJMenuBar(JMenuBar menubar) : Sets the menubar for this frame.
  • public void setLayeredPane(JLayeredPane layeredPane) : Sets the layeredPane property. This method is called by the constructor.
  • public void setLayout(LayoutManager manager) : Sets the LayoutManager.
  • protected void setRootPane(JRootPane root) : Sets the rootPane property. This method is called by the constructor.
  • protected void setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and setLayout are forwarded to the contentPane.
  • public void setTransferHandler(TransferHandler newHandler) : Sets the transferHandler property, which is a mechanism to support the transfer of data into this component. Use null if the component does not support data transfer operations.
  • public void update(Graphics g) : Just calls paint(g).

4. JPanel

JPanel is a generic lightweight container. Let us look at some of the commonly used methods of JPanel. These are inherited from javax.swing.JComponent and java.awt.Container

  • public void setLayout(LayoutManager mgr) : Sets the layout manager for this container. This method changes layout-related information
  • public void setBorder(Border border) : Sets the border of this component. The Border object is responsible for defining the insets for the component

5. JButton

JButton is an implementation of a “push” button. Buttons can be configured, and to some degree controlled by Actions. Some commonly used methods of JButton are:

  • public void setText(String text) : Sets the button’s text.
  • public void setIcon(Icon defaultIcon) : Sets the button’s default icon
  • public void addActionListener(ActionListener l) : Adds an ActionListener to the button.

6. JLabel

A JLabel is a display area for a short text string or an image or both. A label does not react to input events. As a result, it cannot get the keyboard focus. Some commonly used methods are:

  • public void setIcon(Icon icon) : Defines the icon this component will display. If the value of icon is null, nothing is displayed. The default value of this property is null.
  • public void setText(String text) : Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed. The default value of this property is null.

7. Java JFrame Example

Let us now look at an example using the above discussed components.


import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;

public class JFrameExample{
	public static void main(String[] args){
		// Create frame with title Registration Demo
		JFrame frame= new JFrame();	
		frame.setTitle("JFrame Registration Demo");
               // Panel to define the layout. We are using GridBagLayout
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

		JPanel headingPanel = new JPanel();
		JLabel headingLabel = new JLabel("This is the heading panel for our demo course");
               // Panel to define the layout. We are using GridBagLayout
		JPanel panel = new JPanel(new GridBagLayout());
		// Constraints for the layout
		GridBagConstraints constr = new GridBagConstraints();
		constr.insets = new Insets(5, 5, 5, 5);		
		constr.anchor = GridBagConstraints.WEST;

		// Set the initial grid values to 0,0
		// Declare the required Labels
		JLabel userNameLabel = new JLabel("Enter your name :");
		JLabel pwdLabel = new JLabel("Enter your password :");
		JLabel emailLabel = new JLabel("Enter email :");
		// Declare Text fields
		JTextField userNameTxt = new JTextField(20);
		JPasswordField pwdTxt = new JPasswordField(20);
		JTextField emailTxt = new JTextField(20);
		panel.add(userNameLabel, constr);
		panel.add(userNameTxt, constr);
		constr.gridx=0; constr.gridy=1;
		panel.add(pwdLabel, constr);
		panel.add(pwdTxt, constr);
		constr.gridx=0; constr.gridy=2;
		panel.add(emailLabel, constr);
		panel.add(emailTxt, constr);
		constr.gridwidth = 2;
		constr.anchor = GridBagConstraints.CENTER;
                // Button with text "Register"
		JButton button = new JButton("Register");
		// add a listener to button
		button.addActionListener(new ActionListener()
		  public void actionPerformed(ActionEvent e)
			headingLabel.setText("Thanks for registering. We'll get back to you shortly.");
               // Add label and button to panel
               panel.add(button, constr);

		// Add panel to frame
                frame.setSize(400, 400);

Let’s explain the above code. First, we create frame and panel containers by using JFrame and JPanel. We created two panels in this example. The headingPanel contains a label to indicate some details. The second panel holds the required fields, labels and buttons. We used the BoxLayout for the main panel in this example. Next, we add components like labels and button to the panel to the second panel using the GridBagLayout.

Text fields and labels for user name, password, email and button are added to the main panel using JLabel, JTextField, JButton, and JPasswordField. An action listener is defined for the button to reset the fields when the button is clicked. We then declare the size of the window frame and then the location using setLocation(x, y) or the setLocationRelativeTo(component) method. In this case, we use the setLocationRelativeTo(null) that places the frame to the center of the screen. We then define the action of the frame when we press the close button. The close button of the frame by default performs the hide operation for the JFrame. In this example, we changed this behavior to window close operation by setting the setDefaultCloseOperation() to EXIT_ON_CLOSE value. Finally, we make the frame visible by using the setVisible(true) method.

The result would be displayed as below:

Java JFrame - first screen to enter data
Java JFrameFig 3. JFrame example – first screen to enter data
Java JFrame - after data input
Fig 4. JFrame example – after data input
Java JFrame - after Register button is clicked. Note the change in label
Fig 5. JFrame example – after the Register button is clicked. Note the change in label

9. Download the Source Code

That was a JFrame Java Example.

This was an example of how to use the class JFrame.

You can download the source of this tutorial here: Java JFrame Example

Last updated on Aug. 10th, 2021

Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
6 years ago

Thanks a lot!

Rodrigo Santos Ferraracio
Rodrigo Santos Ferraracio
4 years ago

Thanks, i’ve been seach for a material in internet, which teach us, how to make a GUI with code, many examples we find with a IDE tools, i’ts good but, for apprenticeship it’s better learn with coding!!

4 years ago

it dosen’t work

Back to top button