Java Reference
In-Depth Information
Labels
A label is a user component that holds text, an icon, or both. Labels, which are created
from the JLabel class, often are used to identify the purpose of other components on an
interface. They cannot be directly edited by a user.
To create a label, you can use the following constructors:
JLabel( String ) —A label with the specified text
n
JLabel( String , int ) —A label with the specified text and alignment
n
JLabel( String , Icon , int ) —A label with the specified text, icon, and
alignment
n
9
The alignment of a label determines how its text or icon is aligned in relation to the area
taken up by the window. Three static class variables of the SwingConstants interface are
used to specify alignment: LEFT , CENTER , and RIGHT .
The contents of a label can be set with setText( String ) or setIcon( Icon ) methods.
You also can retrieve these things with getText() and getIcon() methods.
The following statements create three labels with left, center, and right alignment,
respectively:
JLabel feedsLabel = new JLabel(“Feeds”, SwingConstants.LEFT);
JLabel urlLabel = new JLabel(“URL: “, SwingConstants.CENTER);
JLabel dateLabel = new JLabel(“Date: “, SwingConstants.RIGHT);
Text Fields
A text field is a location on an interface where a user can enter and modify text using the
keyboard. Text fields are represented by the JTextField class, and each can handle one
line of input. Later in this section, you will see a similar component called a text area
that can handle multiple lines.
Constructors for text fields include the following:
JTextField() —An empty text field
n
JTextField( int ) —A text field with the specified width
n
JTextField( String , int ) —A text field with the specified text and width
n
A text field's width attribute has relevance only if the interface is organized in a manner
that does not resize components. You will get more experience with this when you work
with layout managers on Day 11, “Arranging Components on a User Interface.”
Search WWH ::




Custom Search