Java Reference
In-Depth Information
Display 18.5
Some Methods in the Classes
JButton, JMenuItem,
and
JLabel
(part 2 of 2)
public
JButton(String text, ImageIcon picture)
public
JMenuItem(String text, ImageIcon picture)
public
JLabel(
String text, ImageIcon picture,
int
horizontalAlignment)
Creates a button, menu item, or label with both the
text
and the icon
picture
on it.
horizontalAlignment
is one of the constants
SwingConstants.LEFT,
SwingConstants.CENTER, SwingConstants.RIGHT, SwingConstants.LEADING,
or
SwingConstants.TRAILING.
The interface
SwingConstants
is in the
javax.swing
package.
public void
setText(String text)
Makes
text
the only text on the button, menu item, or label.
public void
setIcon(ImageIcon picture)
Makes
picture
the only icon on the button, menu item, or label.
public void
setMargin(Insets margin)
JButton
and
JMenuItem
have the method
setMargin
, but
JLabel
does not.
The method
setMargin
sets the size of the margin around the text and icon in the button or
menu item. The following special case will work for most simple situations. The
int
values give
the number of pixels from the edge of the button or menu item to the text and/or icon.
public void
setMargin(
new
Insets(
int
top,
int left, int
bottom,
int
right))
The class
Insets
is in the
java.awt
package. (We will not be discussing any other uses for
the class
Insets
.)
public void
setVerticalTextPosition(
int
textPosition)
Sets the vertical position of the text relative to the icon. The
textPosition
should be one of
the constants
SwingConstants.TOP, SwingConstants.CENTER
(the default position), or
SwingConstants.BOTTOM.
The interface
SwingConstants
is in the
javax.swing
package.
public void
setHorizontalTextPosition(
int
textPosition)
Sets the horizontal position of the text relative to the icon. The
textPosition
should be one
of the constants
SwingConstants.RIGHT, SwingConstants.LEFT, SwingConstants.
CENTER, SwingConstants.LEADING,
or
SwingConstants.TRAILING.
The interface
SwingConstants
is in the
javax.swing
package.