Java Reference
In-Depth Information
Creating a JLabel
There are six constructors for
JLabel
:
public JLabel()
JLabel label = new JLabel();
public JLabel(Icon image)
Icon icon = new ImageIcon("dog.jpg");
JLabel label = new JLabel(icon);
public JLabel(Icon image, int horizontalAlignment)
Icon icon = new ImageIcon("dog.jpg");
JLabel label = new JLabel(icon, JLabel.RIGHT);
public JLabel(String text)
JLabel label = new JLabel("Dog");
public JLabel(String text, int horizontalAlignment)
JLabel label = new JLabel("Dog", JLabel.RIGHT);
public JLabel(String text, Icon icon, int horizontalAlignment)
Icon icon = new ImageIcon("dog.jpg");
JLabel label = new JLabel("Dog", icon, JLabel.RIGHT);
With the constructors for
JLabel
, you can customize any of three properties of the
JLabel
:
text
,
icon
, or
horizontalAlignment
. By default, the
text
and
icon
properties are empty,
whereas the initial
horizontalAlignment
property setting depends on the constructor arguments.
These settings can be any of
JLabel.LEFT
,
JLabel.CENTER
, or
JLabel.RIGHT
. In most cases, not
specifying the
horizontalAlignment
setting results in a left-aligned label. However, if only the
initial icon is specified, then the default alignment is centered.
JLabel Properties
Table 4-8 shows the 14 properties of
JLabel
. They allow you to customize the content, position,
and (in a limited sense) the behavior of the
JLabel
.
Table 4-8.
JLabel Properties
Property Name
Data Type
Access
accessibleContext
AccessibleContext
Read-only
disabledIcon
Icon
Read-write bound
displayedMnemonic
char
Read-write bound
displayedMnemonicIndex
int
Read-write bound
horizontalAlignment
int
Read-write bound
horizontalTextPosition
int
Read-write bound