• How to create JFrame in Java

    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.

    Creating a JFrame in Java Example

    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:

    jframe example

    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 are the calling of different methods in creation of a JFrame:

    • frame = new JFrame() – Create an instance of JFrame and store it to the variable frame.
    • frame.setTitle(“My JFrame”) – Set the title of our frame that can be found on the upper-left part of the frame.
    • frame.setSize(500, 400) – Set the size of our frame by 500 in width, 400 in height.
    • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) – set what will happen when we click the X button (close button) on the upper right of the frame. This method means to exit the program when we click the close button.
    • frame.setVisible(true) – Make our frame visible. Setting it to false makes our frame hidden or invisible.

    Now that we have our JFrame, we can now add other UI components to our application. Next tutorial is about adding a JButton in Java.

    Related Post