Java Reference
In-Depth Information
Buttons, Text Fields, and Labels
Our empty frames are not very interesting. Let's look at some graphical components
that can be placed in a frame.
The first component we'll examine is the button. You most likely know that a button
is an onscreen component that can be clicked to cause an action. Buttons are repre-
sented by the JButton class. Each JButton object you create represents one button on
the screen; if you want three buttons, you must create three JButton objects and place
them in your frame.
You can construct a button either with no parameters (a button with no text), or
with a String representing the text on the button. Of course, you can always change
the button's text by calling the setText method on it. You can also set other proper-
ties of the button, such as its background color:
JButton button1 = new JButton();
button1.setText("I'm the first button");
JButton button2 = new JButton("The second button");
button2.setBackground(Color.YELLOW);
A text field is a box into which the user can type text strings. A text field is repre-
sented by a JTextField object, which can be constructed with a parameter specify-
ing the number of characters that should be able to fit in the text field:
// creates a field 8 characters wide
JTextField field = new JTextField(8);
The character width you specify ( 8 in the preceding code) is not enforced by the
program; the user can type more than the specified number of characters if he or she
wishes. The parameter value just affects the size of the text field on the screen.
A label is a string of text that is displayed on the GUI. Labels exist to provide
information and are not generally clicked to perform actions. Labels are often placed
next to text fields so that the user knows what should be typed into the field. A label
is represented by a JLabel object, which can be constructed with a parameter speci-
fying the label's text:
JLabel label = new JLabel("This is a label");
 
Search WWH ::




Custom Search