The JFrame class is slightly incompatible with Frame . 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 . This is different from the AWT Frame case. As a convenience, the add , remove , and setLayout methods of this class are overridden, so that they delegate calls to the corresponding methods of the ContentPane . For example, you can add a child component to a frame as follows: And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame .
Unlike a Frame , a JFrame has some notion of how to respond when the user attempts to close the window. The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method setDefaultCloseOperation(int) . To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) .
For more information on content panes and other features that root panes provide, see Using Top-Level Containers in The Java Tutorial.
In a multi-screen environment, you can create a JFrame on a different screen device. See Frame for more information.
Warning: Swing is not thread safe. For more information see Swing’s Threading Policy.
JFrame basic tutorial and examples
In the code above we create a frame window entitled “Demo program for JFrame”.
2. Setting layout manager
Or using absolute layout:
NOTE: the call setLayout(layout) is equivalent to this call:
3. Adding child components to JFrame
- We can use the method add(Component) to add a component to the frame’s content pane. For example, adding a text field: NOTE: the call add(Component) is equivalent to this call:
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:
4. Specifying window closing behavior for JFrame
We can specify which action will be executed when the user clicks on the frame’s close button:
- Do nothing (default):
- Hide the frame:In this case, the frame becomes invisible. To show it again, call:
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.
5. Showing JFrame on screen
- Make sure we set size for the frame before making it visible:
Or pass a Rectangle object:
6. Handling window events for JFrame
Listen to window events by implementing the WindowListener interface: In this way, have the frame class implements the WindowListener interface and overrides all its methods, like the following example:
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:
Then add this listener for the frame as follows:
Or we can use anonymous class syntax like this:
7. Customizing JFrame’s appearance
- Set icon image for the frame:The icon image is in the file system:
Here the image android.png is placed under directory images which is relative to the application’s directory.
The icon image is in the classpath or in jar files:
If the frame is undecorated, its border, title bar and window buttons are all removed, only keep its content pane visible.
8. JFrame demo program
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.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Java JFrame Tutorial
JFrame is a java swing container that can be used to create application windows. JFrames are the top most container in the swing applications. All the GUI components like labels, comboboxes are added into the JFrame. In this tutorial, we will learn how to make use of the Java JFrames to create swing applications and see how to manage the JFrame windows.
Simple application with JFrame
First, let’s create a simple application. We will add a button to the JFrame container.
This will create the following output
Even though the above code works, it is not perfect. If you run the above code, you will have some questions. Let me make things clear for you.
Question: Even after the JFrame is closed, the application is still running in the background. Why does my application still run after closing the main window?
This is because you haven’t specified what to do when the JFrame is closed. Remember that in a real-world application, there will be many windows, so many JFrames. By default, if the JFrame was exiting/killing the application when it is closed, then this would cause countless issues. Because each window closing will cause the application to terminate by default.
To prevent this, when the close button is pressed, the JFrame just gets hidden and will not exit the application fully. To exit the application on window close, add the following line into the code to set setDefaultCloseOperation.
Question: The JFrame window is opening at the edge of the screen. How to make JFrame center on screen?
By default, the Window will appear at the edge of the screen (most of the time, in most of the common operating systems). To make the JFrame window appear at the dead center of the screen, you need to set the window’s location-relative-to null. It can be done as follows.
Set Icon for JFrame Window
Very often, we will have to set our custom icon to the application window. With JFrame, this is possible with the method JFrame#setIconImage(Image). This will make the icon appear on the OS taskbar as well.
JFrame window with icon shown on taskbar
If you would like to learn how to set up a system tray icon, have a look into this tutorial on setting up of tray-icon with menu in Java.
Close/Hide JFrame Programmatically
Let’s say we want to close a JFrame programmatically. This can be done with JFrame#setVisible(false) method followed by a JFrame#dispose() method to clear the object. There is a deprecated function JFrame#hide(), but you should never use it as it has been deprecated from Java 1.5.
Simply set the visibility of the frame to false, and it will hide/close the window. Then call dispose() to release the system resources used by it.
Another method for closing
Another easy method for closing the JFrame is by simulating the close button click event. As we have already seen, pressing the X button will close the window. We can simply simulate the close button click to close the JFrame itself. We can do that as follows
Maximize and minimize JFrame Programmatically
Now, let’s say we came across a requirement where we need to maximize a JFrame window programmatically. There is a function called JFrame#setExtendedState(int state) for programmatically maximizing and minimizing. Let’s see how we can do that with some code snippet.
In this tutorial, we have learned how to make use of JFrame to create windows in Java. We have seen how to create it, attach icon, center on screen, maximize and minimize etc. If you have liked this article, you might also like the following articles I have written.
JFrame Tutorial in Java with Examples | Java Swing
Hello Friends, Welcome to my new post of Java JFrame Tutorial for Beginners. In my last post we have seen Java Environment Setup in Windows and if you don’t know the basic idea of how to run a Java program then go through my previous post.
In this JFrame in Java Tutorial for beginners , we will see how to create JFrame in Java and how to use JFrame using its associated methods.
So let’s begin JFrame in Java Tutorial,
JFrame in Java Tutorial for Beginners
What is JFrame in Java?
- It is an extended version of Java.awt.Frame that adds support for the JFC/Swing architecture.
- JFrame is the core class of javax.swing package and is used to develop GUI (Graphical User Interface) in which various visual objects like Text Field, Radio Button, Scroll Bar, Check Box etc are embedded. This GUI is called Window pane.
- JFrame is a window with a title Bar, Border, a resizable Border, menu Bar, Buttons that close or iconify the window and a content pane that acts as a container.
- JFrame contains a JRootpane, which is where all of the components are added, and this JRootpane is shared among all container objects. When components are added to a JFrame, they are added to the content pane(JRootpane).
- The JFrame is typically the outermost container used in GUI applications.
So this was all about JFrame in Java, and now we will see how to create JFrame in Java and then how to use JFrame in Java step by step.
How to Create JFrame in Java
Steps For Creating a GUI JFrame in Java
- Import javax.swing.JFrame package, or you can also use javax.swing.* package. This package will make available the JFrame class.
- Create a class and give a name to it.
- Write main method and inside the main method create an object of the JFrame class.
- Now save the program, compile it, and run it.
- The most exciting thing about this program is that although you have successfully compiled and run the program, nothing shows up. It is just because the Frame is invisible. To make it visible, we have to call the setVisible() method of the JFrame class using the JFrame class object.
Setting the visibility of JFrame in Java
- This method is used to control whether a component will be displayed on the screen or not.
- It takes a Boolean value as an argument.
- setVisible(false) –“it hides the component by making it invisible “.
- setVisible(true) –“it reveals the component by making it visible “.
- Save it, compile and run the program. Now you can see the window is visible.
- Now, as you can see, the window is visible, and by default, it opens up in the top-left corner of the screen.
- There is an interesting thing associated with the above program. Although the close button has been clicked, the program will not be removed from the memory because of its TSR(Terminate but stay resident) characteristics. However, Something is missing for the complete termination of the program. The solution is to invoke the setDefaultCloseOperation() method.
Setting the Default Close Operation of JFrame/How to Close a JFame in Java
- This method is called when one clicks the Close Button.
- This method specifies many options for the close Button. We can choose any one of the given constants to determine the close Button’s nature when someone clicks on it. Constants are given below :
- JFrame.DO_NOTHING_ON_CLOSE – “As the name suggests, it neglects the click, and nothing happens when someone clicks on the Close Button. “
- JFrame.HIDE_ON_CLOSE –” As the name suggests, it only hides the frame when someone clicks on the Close Button, but the application still remains on the running state. “
- JFrame.DISPOSE_ON_CLOSE –“As the name suggests, it disposes the frame when someone clicks on the Close Button, but the application still remains on the running state. “
- JFrame.EXIT_ON_CLOSE –“As the name suggests, it exits the application when someone clicks on the Close Button and removes the program from memory permanently. “
- So we have learned how to close a JFrame when we click on the exit button.
Setting The Size Of Java JFrame
- As the name suggests this method is used to set the size of the window displayed on the screen .
- By default the size is passed to the setSize() method is ” 0 pixel x 0 pixel “.
- it takes two integer type arguments. first argument specifies the width of the window and second argument specifies the height of the window . example – setSize(100,200) .
- As we can see the output of the above program in above image and size of the window has been changed.
Setting the Location of JFrame in Java
- As the name suggests, this method is used to set the window’s location on the screen.
- The default location of the window is the top-left corner of the screen.
- It takes two integer type arguments. The first argument specifies the window’s location on the x-axis, and the second argument specifies the window’s location on the y-axis.
- As we can see, the above program’s output in the above image in which the window’s location has been changed in the x-axis and y-axis.
Setting the Size and Location of The Java JFrame Simultaneously
- This method is used to set the size and position(Location) of the window simultaneously.
- It takes four integer type arguments in which the first two arguments specify the window’s position on the x-axis and y-axis, and the last two arguments specify the size of the window in width and height. example –setBounds(200,200,100,200).
Setting The Title Of JFrame in Java
- As the name suggests, this method is used to set the title of the window.
- It takes the string/name of the window to be displayed on the screen as its argument.
- As we can see in the above image, the Title of the window has been created.
Setting Background Color of JFrame in Java
- For this purpose, we have to call the setBackground() method through the object of JFrame. The parameter to be sent is the various static fields of the Color class
Steps to Add Color
- Import the java.awt.* package. This package makes the setBackground() method available.
- Since the Background Color can only be added to the container, we have to make a container object for the window f.
- This is done by calling the getContentPane() method through f.
- Now we have to call the setBackground() method using the container’s object, which takes various static pre-defined fields of Color class.
- As we can see in the above image, the background color of the window has been changed.
Restricting The User To Resize The JFrame in Java
- For this purpose, we call the setResizeable() method of the JFrame class.
- This method takes a boolean value as its parameter.
- setResizable(true) – “allows the user to resize the window. “
- setResizable(false)- “restricts the user to resize the window. “
- As we can see in the above image that it restricts the user to resize the window.
How to add Background Image to JFrame in Java
- This section will learn how to set an image as background in Java JFrame.
- To set an image as background in JFrame, we will create the object of ImageIcon class, and in its constructor, we have to pass the full path of the image/icon with its correct extension.
- If the image is in the same folder we have created the program, then we have to give only the image name and its extension otherwise if the image is in the other folder, then we have to provide the whole path of the picture.
- Then we will create an object of JLabel class, and in its constructor, we will pass the object of ImageIcon class as an argument.
- Then we can set the location and size of the Image/icon using the method setBounds() .
- The interesting thing is that if we don’t know the actual width and height of the image and it does not perfectly fit in the label, then we can use the two methods of icon getIconWidth() and getIconHeight() as arguments in setBounds() method .
- The next thing we have to do is add the label to the frame’s content pane.
- The code is given below.
- As shown in the above image, we have successfully added a background image to JFrame in Java.
So Friends, Now I’m wrapping up this Java JFrame in Java Tutorial in which we have learned how to create a GUI JFrame in Java and how to use that. Please do comment if you are having any doubts or queries regarding this post. For more tutorials about Java and Java Swing, stay tuned with Tutorials Field. Thank You.
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Tic Tac Toe Java Code Against Computer With Source Code
- Calculator Program in Java Swing/JFrame with Source Code
12 thoughts on “JFrame Tutorial in Java with Examples | Java Swing”
Finally I’ve found someone who explain too easy, thanks
Thank you so much for making a tutorial that actually speaks English! Most tutorials move too fast and assume you know something already. This was super helpful ?
Thank you so much for helping me.
You are welcome
I appreciate that
Thanks, it is good explanation
wonderful presentation indeed
This is perfectly fine and is in very simple to learn and understand step by step.
This is too early but i can say, You are the best. wooooooooooooooow, My java Teacher has made java lessons cut and past for my class and the student are also doing chew and pour. those of us who can’t do the chew and pour are left behind. I always said there’s no hope in my coding journey? but you have proven that there’s hope ahead. i never knew i could understand “GUI” tutorials. Please help me with a full java tutorial to learn. Is there any link ?
Thank you so much! I really appreciate your explanation from scratch and covering the entire concept.