Table of content:
JFrame is a Swing’s top-level container that renders a window on screen. A frame is a base window on which other components rely, such as menu bar, panels, labels, text fields, buttons, etc. Almost every Swing application starts with JFrame window. This article provides a summary of common practices when using JFrame in Swing development.
public class SwingJFrameDemo extends javax.swing.JFrame { public SwingJFrameDemo() { super("Demo program for JFrame"); } }
JFrame frame = new JFrame("Demo program for JFrame");
In the code above we create a frame window entitled “Demo program for JFrame”.
The default layout of the frame is BorderLayout, we can set another layout like this:
frame.setLayout(new GridBagLayout());
Or:
frame.setLayout(new GridLayout());
Or:
frame.setLayout(new CardLayout());
Or:
frame.setLayout(new FlowLayout());
Or using absolute layout:
frame.setLayout(null);
NOTE: the call setLayout(layout) is equivalent to this call:
frame.getContentPane().setLayout(layout);
JTextField textFieldUserName = new JTextField(50); frame.add(textFieldUserName);
NOTE: the call add(Component) is equivalent to this call:
frame.getContentPane().add(Component);
add(textFieldUserName, BorderLayout.CENTER);
GridBagConstraints constraint = new GridBagConstraints(); constraint.gridx = 1; constraint.gridy = 0; // set other constraints... JTextField textFieldUserName = new JTextField(20); add(textFieldUserName, constraint);
The method setJMenuBar(JMenuBar) is used to add a menu bar to the frame. The following example code adds a menu bar with a File > Exit menu:
JMenuBar menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); JMenuItem menuItemExit = new JMenuItem("Exit"); menuFile.add(menuItemExit); menuBar.add(menuFile); // adds menu bar to the frame frame.setJMenuBar(menuBar);
Image:
We can specify which action will be executed when the user clicks on the frame’s close button:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
In this case, the frame becomes invisible. To show it again, call:
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
In this case, the frame is removed and any resources used by the frame are freed. If the frame is the last displayable window on screen, the JVM may terminate.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200); frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingJFrameDemo().setVisible(true); } });
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocation(100, 100);
frame.setLocation(new java.awt.Point(100, 100));
We can use the setBounds(x, y, width, height) method to set size and location of the frame in one call:
frame.setBounds(100, 100, 300, 400);
Or pass a Rectangle object:
frame.setBounds(new java.awt.Rectangle(100, 100, 300, 400));
If we don’t want to specify or (don’t know) the exact size of the frame, we can use the method pack() to let the frame resizes itself in a manner which ensures all its subcomponents have their preferred sizes:
frame.pack();
frame.setAlwaysOnTop(true);
The interface java.awt.event.WindowListener defines various window events to which we can listen if interested. The method addWindowListener(WindowListener) of JFrame class is used to add a window listener for the frame.
In this way, have the frame class implements the WindowListener interface and overrides all its methods, like the following example:
public class FrameDemo extends JFrame implements WindowListener { public FrameDemo() { super("Frame Demo"); // initialization code... setSize(300, 400); addWindowListener(this); setVisible(true); } public void windowActivated(WindowEvent event) { System.out.println("The window has been activated"); } public void windowClosed(WindowEvent event) { System.out.println("The window has been closed"); } public void windowClosing(WindowEvent event) { System.out.println("About to close the window"); } public void windowDeactivated(WindowEvent event) { System.out.println("The window has been deactivated"); } public void windowDeiconified(WindowEvent event) { System.out.println("The window has been restored"); } public void windowIconified(WindowEvent event) { System.out.println("The window has been minimized"); } public void windowOpened(WindowEvent event) { System.out.println("The window has been opened"); } }
In case we want to listen to only one (or more, but not all) events, we can create a listener class that extends from the WindowAdapter class and override only the interested event methods:
class MyWindowListener extends WindowAdapter { // overrides only one method: public void windowClosing(WindowEvent event) { System.out.println("About to close the window"); } }
Then add this listener for the frame as follows:
MyWindowListener listener = new MyWindowListener(); frame.addWindowListener(listener);
Or we can use anonymous class syntax like this:
addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { System.out.println("About to close the window"); } });
The icon image is in the file system:
Image icon = new javax.swing.ImageIcon("images/android.png").getImage(); frame.setIconImage(icon);
Here the image android.png is placed under directory images which is relative to the application’s directory.
Image:
The icon image is in the classpath or in jar files:
String iconPath = "/net/codejava/swing/jframe/android.png"; Image icon = new ImageIcon(getClass().getResource(iconPath)).getImage(); frame.setIconImage(icon);
Here the image android.png is placed under the package net.codejava.swing.jframe of the application.
NOTE: if the image could not be found, the frame still has the default icon - which is the coffee cup.
By default, the users can resize the frame. Use the following code if we want to prevent the frame from being resized:
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GREEN);
frame.setUndecorated(true);
If the frame is undecorated, its border, title bar and window buttons are all removed, only keep its content pane visible.
To demonstrate the techniques mentioned in this article and for your reference, we create a Swing program looks like the following:
On clicking the close button, a confirm message dialog appears:
If “Yes” is selected, the program exits, otherwise the frame remains visible on screen.
You can download this demo program’s source code and executable jar file in the attachments section.