Java Reference
In-Depth Information
JButton Properties
The
JButton
component doesn't add much to the
AbstractButton
. As Table 4-14 shows, of the
four properties of
JButton
, the only new behavior added is enabling the button to be the default.
Table 4-14.
JButton Properties
Property Name
Data Type
Access
accessibleContext
AccessibleContext
Read-only
defaultButton
boolean
Read-only
defaultCapable
boolean
Read-write bound
UIClassID
String
Read-only
The default button tends to be drawn with a different and darker border than the remaining
buttons. When a button is the default, pressing the Enter key while in the top-level window
causes the button to be selected. This works only as long as the component with the input
focus, such as a text component or another button, doesn't consume the Enter key. Because
the
defaultButton
property is read-only, how (you might be asking) do you set a button as the
default? All top-level Swing windows contain a
JRootPane
, to be described in Chapter 8. You tell
this
JRootPane
which button is the default by setting its
defaultButton
property. Only buttons
whose
defaultCapable
property is
true
can be configured to be the default. Figure 4-13 shows
the top-right button set as the default.
Figure 4-13.
Setting a default button
Listing 4-6 demonstrates setting the default button component, as well as using a basic
JButton
. If the default button appearance doesn't seem that obvious in Figure 4-13, wait until
the
JOptionPane
is described in Chapter 9, where the difference in appearance will be more
obvious. Figure 4-13 uses a 2-by-2
GridLayout
for the screen. The extra two arguments to the
constructor represent gaps to help make the default button's appearance more obvious.