Displaying a window with Swing

Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

Java comes with a GUI library called Swing. In this article, we have checked a program that displays a window.

Display a window with a width of 250 and a height of 150

The following is a sample window that will display a 250×150 window.

Source
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(250, 150);
        setVisible(true);
    }

}

The Test class in the above sample program inherits from the JFrame class.

JFrame inherits the class as follows.

java.lang.Object
└java.awt.Component
 └java.awt.Container
  └java.awt.Window
   └java.awt.Frame
    └javax.swing.JFrame

It creates an instance of itself in the main method.

The constructor contains the minimum description.

The method call “setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);" sets the behavior to close the application when the window close button is pressed. If this is not specified, HIDE_ON_CLOSE will be set by default. In that case, when the X button of the window is pressed, it will “hide the frame". So, the program will remain running.

The setSize method is a method inherited from java.awt.Window. The arguments are in turn “width" and “height". Here, the width is in pixels. In the sample, width 250 and height 150 are specified.

The method setVisible is a method inherited from java.awt.Window. The argument is of type boolean, and if true, the Window will be displayed.

To set the title

When you run the sample, the title bar appears, but the title is not set. The setTitle method can be used to set the title. This method is an inherited method from java.awt. The argument is a string. The description is 'setTitle(“Title");’.

swing_day001_001_settitle

To disable resizing

In the sample, the window size can be changed by mouse operation. To disable this operation, use the setResizable method. This method is inherited from java.awt. The argument is of type boolean; setting it to false disables the resizing.

To display in the center of the screen

In the sample, the window is displayed in the upper left corner of the desktop. The setLocationRelativeTo method can be used to set the displayed location to the center of the desktop. This method is an inherited method from java.awt. The argument is a Component type. If you specify null as the argument, the window will be placed in the center of the screen.
If it is not null, the behavior changes depending on whether the Component specified in the argument is shown or not. The details are omitted in this article.

That’s all. I hope this is helpful to you.

Articles next and previous in the same category