您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

previous.gif
 (3087 bytes) next.gif
 (2959 bytes)


Content Index Content Page # 18

Temperature conversion example

Example of input/output interaction using text field objects.

When the user enters the centigrade temperature e.g. an integer, followed by the enter key, the Farenheit conversion is calculated and displayed .

When the applet runs it looks like this:

//

<applet code = "TempConversion.class" width = 300 height = 200></applet>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import java.awt.*;

import java.applet.Applet;

import java.awt.event.*;

public class TempConversion extends Applet implements ActionListener {

Label CentrigradeLabel, FarenheitLabel;

       TextField CentIn, FarOut;        

       int f, c, answer;                

     public void init(){

        CentigradeLabel = new Label("Enter Centigrade temperature ");

              CentIn = new TextField(5);

              FarenheitLabel = new Label ("Temperature Farenheit ");

              FarOut = new TextField(5);

              add(CentigradeLabel);

              add(CentIn);

               CentIn.addActionListener(this);

              add(FarenheitLabel);

              add(FarOut);

       }

       public int convert(int x){

              answer = (((9*x)/5)+ 32);

              return answer;

       }

       public void actionPerformed( ActionEvent e){

              if (e.getSource()==CentIn)

              {

              c = Integer.parseInt(CentIn.getText());

              f = convert(c);

              FarOut.setText(Integer.toString(f));

              }

       }

}

The Java event handling framework in the given example:

1. Line 4. The class TempConversion implements ActionListener

2. Line 6 The GUI variable CentIn is declared: TextField CentIn

3. Line 10 The new instance of the CentInt textField is created CentIn = new TextField(5);

4. Line 14 The GUI is added to the Window so it can be displayed add(CentIn);

5. Line 15 informs the ActionListener that the CentIn object will respond to text field events CentIn.addActionListener(this);

6. Line 23 actionPerformed will be invoked when an event i.e. value entered into the TextField CentIn followed by the Enter key takes place passing this information to the ActionEvent object e. The method getsource() will detect which component caused the event. The operations that we want to take place in the application are defined on lines 26 - 28.

Back to top

basicline.gif (170 bytes)