Java Applet,可实现摄氏温度和华氏温度的一键换算:
package example;
//Convert between Celsius and Fahrenheit temperature
//Java how to program, 5/e, Exercise 6.23
//Neglect the error message when closing the applet since it is a JDK bug (id:5098186)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class Celsius_Fahrenheit extends JApplet implements ActionListener {
double celsius,fahrenheit;
String celsiusText,fahrenheitText;
JLabel CelsiusLable,FahrenheitLable;
JTextField CelsiusField,FahrenheitField;
DecimalFormat twoDigits=new DecimalFormat("0.00");
public void init()
{
Container container=getContentPane();
container.setLayout(new FlowLayout());
CelsiusLable= new JLabel("Enter Celsius Temperature:");
container.add(CelsiusLable);
CelsiusField=new JTextField(10);
container.add(CelsiusField);
CelsiusField.addActionListener(this);
FahrenheitLable= new JLabel("Enter Fahrenheit Temperature:");
container.add(FahrenheitLable);
FahrenheitField=new JTextField(10);
container.add(FahrenheitField);
FahrenheitField.addActionListener(this);
}
public void actionPerformed (ActionEvent event)
{
if (event.getSource()==CelsiusField)
{
celsius=Double.parseDouble(CelsiusField.getText());
fahrenheit=celsius*9.0/5.0+32;
fahrenheitText=twoDigits.format(fahrenheit);
FahrenheitField.setText(fahrenheitText);
}
else if (event.getSource()==FahrenheitField)
{
fahrenheit=Double.parseDouble(FahrenheitField.getText());
celsius=(fahrenheit-32)*5.0/9.0;
celsiusText=twoDigits.format(celsius);
CelsiusField.setText(celsiusText);
}
}
}
运行截屏: