这是个华氏和摄氏温度转换的一个小程序,txtfield1和txtfield2分别是让你输入摄氏和华氏温度,我现在的问题是在ActionListener里,不知道怎么才能将两个文本框的输入内容区分开,求教各位高手帮帮忙.希望能尽可能的详细
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class TemperatureConverter extends JApplet {
private JLabel label1, label2, label3, label4, label5, label6; // Labels
private JTextField txtfield1, txtfield2; // Text Field
private DegCHandler celsiusHnd; // ActionEvent handler
public void init() {
getContentPane().setLayout(new FlowLayout());
celsiusHnd = new DegCHandler(this);
label1 = new JLabel("degrees Celsius:", JLabel.RIGHT);
getContentPane().add(label1);
txtfield1 = new JTextField("0.00", 10);
txtfield1.addActionListener(celsiusHnd);
getContentPane().add(txtfield1);
label2 = new JLabel("degrees Fahrenheit:", JLabel.RIGHT);
getContentPane().add(label2);
label3 = new JLabel("32.00");
getContentPane().add(label3);
label4 = new JLabel("degrees Fahrenheit:", JLabel.RIGHT);
getContentPane().add(label4);
txtfield2 = new JTextField("0.00",10);
txtfield2.addActionListener(celsiusHnd);
getContentPane().add(txtfield2);
label5 = new JLabel("degrees Celsius:", JLabel.RIGHT);
getContentPane().add(label5);
label6 = new JLabel("-17.78");
getContentPane().add(label6);
}
public void toF(double degC) {
DecimalFormat df = new DecimalFormat("0.00");
double degF = (9.0/5.0)*degC + 32;
txtfield1.setText(df.format(degC));
label3.setText(df.format(degF));
}
public void toC(double degF) {
DecimalFormat dc = new DecimalFormat("0.00");
double degC = (degF-32)*(5.0/9.0);
txtfield2.setText(dc.format(degF));
label6.setText(dc.format(degC));
}
// Main method to create Frame
public static void main(String[] s) {
// Create a frame to hold the application
JFrame fr = new JFrame("CtoFConverter ...");
fr.setSize(250,200);
// Create and initialise a CtoFConverter object
CtoFConverter tf = new CtoFConverter();
tf.init();
tf.start();
// Add the object to the center of the frame
fr.getContentPane().add(tf, BorderLayout.CENTER);
// Display the frame
fr.setVisible(true);
}
}
class DegCHandler implements ActionListener {
private TemperatureConverter tc;
public DegCHandler(TemperatureConverter t) {
tc = t;
}
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
double degC = Double.parseDouble(input);
tc.toF(degC);
}
}