• The JFrame

    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.

    Example

    package com.javapointers.javase;
    
    import javax.swing.JFrame;
    
    /**
     *
     * @author javapointers
     */
    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, the output will be:

    Explanation: 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.

    Related Post