Java Reference
In-Depth Information
FIGURE 12.2: Degree converter program.
user cannot see our design. The north panel consists of two components: a label and a text
field.
A label can be created by instantiating an object from the JLabel class. The text
of the label goes in the constructor of the class. The label is usually added to a frame
or a panel using the add method.
A text field can be created by instantiating in an object from the JTextField
class. Constructors of the object take as input the approximate size of the text field
(in characters) and/or the initial text of the text field. The text field is usually added
to a frame or panel using the add method.
For example, the north panel can be created as follows.
JPanel cPanel = new JPanel () ;
cPanel .add( new JLabel( "Celsius: " ));
JTextField cField = new JTextField(20) ;
cPanel .add( cField) ;
The number 20 in the constructor of the JTextField class represents the approximate
size of the text field in characters. Since every character can have a different width, this is
an approximate number. Since the default layout for a panel is the flow layout with center
placement, the label and the text field will be centered in the middle of the panel. The panel
can be added to the window as follows.
add(cPanel , BorderLayout .NORTH) ;
This means that the panel will be added at the north part of the window. This syntax
is allowed because the default layout for the window is the border layout.
Below is the complete code for the degree converter program. Note that the getText
method can be used to retrieve the text from a text field, while the setText method can
be used to set it. The trim method removes leading and trailing spaces. It is always a good
idea to call it after reading a string from a text field.
import java .awt . ;
import java .awt. event . ;
import javax . swing . ;
public class DegreeConverter {
public static void main(String [] args) {
ConverterFrame f = new ConverterFrame () ;
f . setVisible( true );
 
Search WWH ::




Custom Search