📄 ctofconverter.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class CtoFConverter extends JApplet {
private JLabel label1, label2, label3; // Labels
private JTextField txtfield1,txtfield2; // Text Field
private DegCHandler celsiusHnd; // ActionEvent handler
private FahCHandler fahrenheitHnd;
public void init() {
getContentPane().setLayout(new FlowLayout());
celsiusHnd = new DegCHandler(this);
fahrenheitHnd=new FahCHandler(this);
label1 = new JLabel("degrees Celsius:", JLabel.RIGHT);
getContentPane().add(label1);
txtfield1 = new JTextField("0.00", 10);
txtfield1.addActionListener(celsiusHnd);
getContentPane().add(txtfield1);
txtfield2 = new JTextField("32.00", 10);
txtfield2.addActionListener(fahrenheitHnd);
getContentPane().add(txtfield2);
label2 = new JLabel("degrees Fahrenheit:", JLabel.RIGHT);
getContentPane().add(label2);
}
public void toF(double degC) {
DecimalFormat df = new DecimalFormat("0.00");
double degF = (9.0/5.0)*degC + 32;
txtfield1.setText(df.format(degC));
txtfield2.setText(df.format(degF));
}
public void toC(double degF) {
DecimalFormat df = new DecimalFormat("0.00");
double degC = (degF-32)*5.0/9.0;
txtfield2.setText(df.format(degF));
txtfield1.setText(df.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,100);
// 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);
}
}
/**
* This class is the ActionListener of Celsius to Fahrenheit translator.
*/
class DegCHandler implements ActionListener {
private CtoFConverter tc;
public DegCHandler(CtoFConverter t) {
tc = t;
}
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
double degC = Double.parseDouble(input);
tc.toF(degC);
}
}
/**
* This class is the ActionListener of Fahrenheit to Celsius translator.
*/
class FahCHandler implements ActionListener {
private CtoFConverter tc;
public FahCHandler(CtoFConverter t) {
tc = t;
}
public void actionPerformed(ActionEvent e) {
String input = e.getActionCommand();
double degF = Double.parseDouble(input);
tc.toC(degF);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -