Java Reference
In-Depth Information
In lines 12-15, a new JPanel object is created, and the three buttons are added to the
panel by calls to its add() method. When the panel contains all the buttons, the frame's
add() method is called in line 16 with the panel as an argument, adding it to the frame.
If you click the buttons, absolutely nothing happens. Doing some-
thing in response to a button click is covered on Day 12,
“Responding to User Input.”
NOTE
Working with Components
Swing offers more than two dozen different user interface components in addition to the
buttons and containers you have used so far. You will work with many of these compo-
nents for the rest of today and on Day 10, “Building a Swing Interface.”
All Swing components share a common superclass, javax.swing.JComponent , from
which they inherit several methods you will find useful in your own programs.
The setEnabled( boolean ) method determines whether a component can receive user
input (an argument of true ) or is inactive and cannot receive input ( false ). Components
are enabled by default. Many components change in appearance to indicate when they
are not presently usable—for instance, a disabled JButton has light gray borders and
gray text. If you want to check whether a component is enabled, you can call the
isEnabled() method, which returns a boolean value.
The setVisible( boolean ) method works for all components the way it does for con-
tainers. Use true to display a component and false to hide it. There also is a boolean
isVisible() method.
The setSize( int , int ) method resizes the component to the width and height specified
as arguments, and setSize( Dimension ) uses a Dimension object to accomplish the same
thing. For most components, you don't need to set a size—the default is usually accept-
able. To find out the size of a component, call its getSize() method, which returns a
Dimension object with the dimensions in height and width instance variables.
As you will see, similar Swing components also have other methods in common, such as
setText() and getText() for text components and setValue() and getValue() for
components that store a numeric value.
 
Search WWH ::




Custom Search