How to make a jframe by java swing with detail example

     In this article we will learn some basic operations to create a Jframe by java swing - that is the framework of the application.

Example 1: Create a 250 × 200 frame with the title "HelloWorld" displayed at coordinates (300, 200) on the screen.
how-to-make-a-jframe-by-java-swing
We have four constructors for a JFrame by java swing:

JFrame (): Initialize a new frame invisible
JFrame (GraphicsConfiguration qc): Create a specified frame GraphicsConfiguration of the device screen and white headers.
JFrame (String title): Create a new frame invisibile with the specified title
JFrame (String title, GraphicsConfiguration qc): Creates a specified frame and the GraphicsConfiguration of the device screen.

In the above example, we use the third initialization method to set the title for the frame.

how-to-make-a-jframe-by-java-swing

       SetDefaultCloseOperation (int operation): Set the default action that occurs when the user closes the JFrame. If you do not use this function to set the default HIDE_ON_CLOSE (1) - When closed frame will be hidden but not closed.

Other options include:

DO_NOTHING_ON_CLOSE (0) - do nothing
DISPOSE_ON_CLOSE (2) - Only close the frame, other related frames will not be closed.
EXIT_ON_CLOSE (3) - Close all frames related to it.

The setSize function sets the frame size.
The setLocation function sets the position of the frame on the screen. If you want to set the frame to be in the center of the screen use the setLocationRelativeTo (null)
SetVisible sets the display for the frame. If not called or set to false for this function, the frame will not be displayed.

Example 2: Create a JFrame by java swing by inheriting the JFrame class.

how-to-make-a-jframe-by-java-swing
The output:
how-to-make-a-jframe-by-java-swing

     In the second example, our class inherits the JFrame class, so it's a JFrame, so in the HelloWorld1 initialization we can instantly call JFrame methods.
Also in this example are two methods add () and pack (). The add method lets us add an object to the frame (here is a JLabel), the pack method that makes the frame size just enough for the content of the frame even if we set the frame size to be larger.
The setResizable (boolean resizable) method used to set the frame whether it can be resized.


More about how to use this keyword in java with detail example:

Comments