Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Using Components 177

The pageLabellabel is set up with the text “Web page address:” and a
JLabel.RIGHTargument. This last value indicates that the label should
appear flush right. JLabel.LEFTaligns the label text flush left, and JLabel.
CENTERcenters it. The argument used with JTextFieldindicates the text field
should be approximately 20 characters wide. You also can specify default text
that appears in the text field with a statement such as the following:


JTextField country = new JTextField(“US”, 29);


This statement would create aJTextFieldobject that is 20 characters wide
and has the text US in the field.


You can retrieve the text contained within the object with the getText()
method, which returns a string:


String countryChoice = country.getText();


As you might have guessed, you also can set the text with a corresponding
method:


country.setText(“Separate Customs Territory of Taiwan, Penghu, Kinmen,
and Matsu”);


This sets the text to the official name of Chinese Taipei, which is the
longest country name in the world.


Check Boxes


AJCheckBox component is a box next to a line of text that can be checked
or unchecked by the user. The following statements create a JCheckBox
object and add it to a container:


JCheckBox jumboSize = new JCheckBox(“Jumbo Size”);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(jumboSize);


The argument to the JCheckBox()constructor indicates the text to be dis-
played alongside the box. If you want the box to be checked, you use the
following statement instead:


JCheckBox jumboSize = new JCheckBox(“Jumbo Size”, true);


FIGURE 13.3
Displaying labels and text fields.
Free download pdf