How to Create the Most Basic Java Window
By Stephen Bucaro
On Microsoft Windows, a lot of Java programming involves creating command line applications.
But I like to get to opening a graphic window as quickly as possible. This is no problem
because it's actually very easy to create a basic JFrame window.
The methods required to create a windows are in the javax.swing library. The swing library
includes classes to make buttons, check boxes, list boxes, menus, varius types of panes,
tabs, tables, text areas, and many more graphical user interface components.
In the example code shown below, after I import the javax.swing library, I create the
applications class named JFrameDemo which contains the main function, the starting
point for every java application.
public class JFrameDemo
public static void main(String s)
JFrame frame = new JFrame("JFrame Demo");
In the main function I create a new JFrame object named frame. Next I call the
setDefaultCloseOperation method, which takes a constant that defines what
happens when you click the frames close button:
|DO_NOTHING_ON_CLOSE||Ignore the click|
|HIDE_ON_CLOSE||Hide the frame, but keep the application running|
|DISPOSE_ON_CLOSE||Dispose of the frame, but keep the application running|
|EXIT_ON_CLOSE||Exit the application|
Next I call the setSize method, passing it the width and height (in pixels)
of the window. The resulting size will include the title bar, menu, border, ect.
Next I call the setLocationRelativeTo method, which sets the location of the window
relative to a specified component. If the specified component is not currently visible, or
the value passed is null, the window is centered on the screen.
Next I call the setVisible method. setVisible(true) makes the window visible.
setVisible(false) makes the windows invisible.
On the Microsoft Windows operating system, Java applications are often run from DOS
batch files, but when the batch file closes, so does the Java application. You can
prevent this by using the DOS pause command, which will keep the command window
open until the user hits a key. But in the case of a graphical window, you may want
to get rid of the command window while leaving the java application window open.
You can accomplish this by, instad of calling java to execute the application,
use the DOS start command to call javaw to execute the application.
start javaw JFrameDemo2
The javaw command requires no associated command window to remain running,
and the DOS start command closes the command window immediately after it
has executed the batch file's last command.