CelsiusConverter
- Java Tutorial 5.0 英文版Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
CelsiusConverter
Our next example,CelsiusConverter
is actually useful: It is a simple conversion tool. The user enters a temperature in degrees Celsius and clicks theConvert...
button, and a label displays the equivalent in degrees Fahrenheit.Let's examine the code to see how CelsiusConverter
parses the number entered in theJTextField
. First, here's the code that sets up theJTextField
:The integer argument passed in theJTextField tempCelsius = null; ... tempCelsius = new JTextField(5);JTextField
constructor--5
in the example--indicates the number of columns in the field. This number is used along with metrics provided by the current font to calculate the field's preferred width, which is used by layout managers. This number does not limit how many character the user can enter.We want to perform the conversion when the user clicks the button or presses Enter in the text field. To do so, we add an action event listener to the
convertTemp
button andtempCelsius
text field.The event-handling code goes into theconvertTemp.addActionListener(this); tempCelsius.addActionListener(this); ... public void actionPerformed(ActionEvent event) { //Parse degrees Celsius as a double and convert to Fahrenheit. int tempFahr = (int)((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32); fahrenheitLabel.setText(tempFahr + " Fahrenheit"); }actionPerformed
method. It calls thegetText
method on the text field,tempCelsius
, to retrieve the data within it. Next it uses theparseDouble
method to parse the text as a double-precision floating-point number before converting the temperature and casting the result to an integer. Finally, it calls thesetText
method on thefahrenheitLabel
to make the label display the converted temperature.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.