Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

172 HOUR 13:Building a Simple User Interface


The size of the frame can be established by calling its setSize()method
with two arguments: the width and height. The following statement sets
up a frame that is 350 pixels wide and 125 pixels tall:
setSize(350, 125);

Another way to set the size of a frame is to fill it with components, and
then call the frame’s pack()method with no arguments:
pack();

The pack()method sets the frame big enough to hold the preferred size of
each component inside the frame (but no bigger). Every interface compo-
nent has a preferred size, though this is sometimes disregarded, depending
on how components have been arranged within an interface. You don’t
need to explicitly set the size of a frame before calling pack()—the method
sets it to an adequate size before the frame is displayed.
Every frame is displayed with a button along the title bar that can be used
to close the frame. On a Windows system, this button appears as an X in
the upper-right corner of the frame. To define what happens when this
button is clicked, call the frame’s setDefaultCloseOperation()method
with one of four JFrameclass variables as an argument:

. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)—Exit the pro-
gram when the button is clicked.
. setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)—Close the
frame and keep running the application.
. setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)—Keep
the frame open and continue running.
. setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)—Close the
frame and continue running.


A graphical user interface createdwith Swing can customize its appear-
ance with a look and feel, a visual theme that controls how buttons and
other components appear and how they behave.
Java 7 introduces an enhanced look and feel called Nimbus, but it must be
turned on to be used in a class. You set a look and feel by calling the
setLookAndFeel() method of the UIManagerclass in the main Swing
package. The method takes one argument: the full name of the look and
feel’s class.
Free download pdf