How to create a Simple Frame

In this tutorial we will learn how to create a simple frame using swing. There are classes available in swing for every GUI components i.e JFrame, JButton etc.

Let's see now code to create first frame in swing

Program

/* 
   Simple frame using Swing 
   www.jgyan.com
*/
import javax.swing.*;
class firstFrame
 {
  public static void main(String arg[])
   {
    JFrame jf=new JFrame("First Frame");
    jf.setSize(400,400);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
 }

Execution

C:/jgyan/Desktop> javac firstFrame.java
 C:/jgyan/Desktop> java firstFrame

Explanation

To use swing API, swing package has to be imported in program. Following line import swing package. Swing package was not part of first java release, it was added later that's why it is available in javax package (x stands for extension).

import javax.swing.*;

In first line we create object of JFrame class which will make a window on screen, but this windows is hidden by default. In constructor of JFrame class String is passed which will be set as title of window.

 JFrame jf=new JFrame("First Frame");

Second line actually setting size of window. First argument specify width and second argument specify height of frame.

jf.setSize(400,400);

In third line we are making our window visible. In case if we want to hide it, we will pass false.

jf.setVisible(true);

Last line actually specifying what should happen when user click on close button. JFrame.EXIT_ON_CLOSE value will terminate the application, when user click close button.

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setDefaultCloseOperation() method

This method is used to set close operation for window. Following are the values which can be used.

  • JFrame.EXIT_ON_CLOSE

    This option terminate application. So when user click on close button frame will disappear and application terminates.


  • JFrame.HIDE_ON_CLOSE

    This option simply hide the window and keep application running.


  • JFrame.DISPOSE_ON_CLOSE

    This option will destroy frame object and keep application running. In case if there is only one frame then JVM will terminate the application as well.


  • JFrame.DO_NOTHING_ON_CLOSE

    As name implies this option doesn't do anything on pressing of close button.