Java Reference
In-Depth Information
EXAMPLE: A Simple Window
Display 17.2 contains a Swing program that produces a simple window. The window
contains nothing but a button on which is written "Click to end program." If
the user follows the instructions and clicks the button with his or her mouse, the
program ends.
The import statements give the names of the classes used and which package they
are in. What we and others call the Swing library is the package named javax.swing .
The AWT library is the package java.awt . Note that one package name contains an
"x" and one does not.
This program is a simple class definition with only a main method. The first line
in the main method creates an object of the class JFrame . That line is reproduced as
follows:
JFrame firstWindow = new JFrame();
This is an ordinary declaration of a variable named firstWindow and an
invocation of the no-argument constructor for the class JFrame . A JFrame object is a
basic window that includes a border and the usual three buttons for minimizing the
window down to an icon, changing the size of the window, and closing the window.
These buttons are shown in the upper-right corner of the window, which is typical,
but if your operating system normally places these buttons someplace else, that is
where they will likely be located in a JFrame on your computer.
The initial size of the JFrame window is set using the JFrame method setSize ,
as follows:
firstWindow.setSize(WIDTH, HEIGHT);
In this case, WIDTH and HEIGHT are defined int constants. The units of measure
are pixels, so the window produced is 300 pixels by 200 pixels. (The term pixel is
defined in the box entitled “Pixel.”) As with other windows, you can change the size
of a JFrame by using your mouse to drag a corner of the JFrame window.
The buttons for minimizing the window down to an icon and for changing the
size of the window behave as they do in any of the other windows you have used. The
minimization button shrinks the window down to an icon. (To restore the window,
click the icon.) The second button changes the size of the window back and forth
from full screen to a smaller size. The close-window button can behave in different
ways depending on how it is set by your program.
The behavior of the close-window button is set with the JFrame method
setDefaultCloseOperation. The line of the program that sets the behavior of the
close-window button is reproduced next:
firstWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
(continued)
 
Search WWH ::




Custom Search