One of the foundation of graphical user interface (GUI) is a JFrame which holds the other components in your GUI. This article will teach you on how to create JFrame in Java.
The JFrame class is a subclass of Frame in java.awt package. JFrame adds support for the JFC/Swing component architecture. 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.
The JFrame component holds all the other components. It is the window of the application. You can set the title of the application in JFrame which commonly found on the upper left side of the application. It also contains the minimize, maximize and close buttons. Lets proceed now on how to create a jframe in java.
package com.javapointers.javase; import javax.swing.JFrame; public class JFrameTest { JFrame frame; public JFrameTest() { //this is the constructor frame = new JFrame(); frame.setTitle("My JFrame"); frame.setSize(500, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String args[]) { //main method JFrameTest test = new JFrameTest(); } }
When we run the program, it should open our JFrame:
In our example, we have created a new class named JFrameTest. We have imported javax.swing.JFrame to be able to use the JFrame component. Inside our constructor is the calling of different methods in the creation of a JFrame:
Now that we have our JFrame, we can now add other UI components to our application. The next tutorial is about adding a JButton in Java.