代码:
package test1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WenDu extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel row1 = new JPanel();
JLabel a=new JLabel("摄氏温度");
JLabel b=new JLabel("华氏温度");
JPanel row2 = new JPanel();
JButton button = new JButton("==>");
JPanel row3 = new JPanel();
JTextField text=new JTextField(5);
JTextField text1=new JTextField(5);
JPanel row4 = new JPanel();
JButton button1 = new JButton("<==");
WenDu(){
setTitle("摄氏温度和华氏温度转化");
setSize(300,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
row1.setLayout(new BoxLayout(row1, BoxLayout.X_AXIS));
row1.add(a);
row1.add(Box.createHorizontalStrut(160));
row1.add(b);
row2.setLayout(new BoxLayout(row2, BoxLayout.X_AXIS));
row2.add(button);
row3.setLayout(new BoxLayout(row3, BoxLayout.X_AXIS));
row3.add(text);
row3.add(Box.createHorizontalStrut(50));
row3.add(text1);
row4.setLayout(new BoxLayout(row4, BoxLayout.X_AXIS));
row4.add(button1);
panel.add(row1);
panel.add(row2);
panel.add(row3);
panel.add(row4);
add(panel);
button.addActionListener(this);
button1.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// 摄氏温度转化华氏温度
if(e.getSource()==button) {
String str=text.getText();
Double d=Double.valueOf(str);
Double d1=d*9/5+32;
text1.setText(String.valueOf(d1));
// 华氏温度转化摄氏温度
}else if(e.getSource()==button1) {
String str=text1.getText();
Double d=Double.valueOf(str);
Double d1=(d-32)*5/9;
text.setText(String.valueOf(d1));
}
}
public static void main(String[] args) {
WenDu demo=new WenDu();
demo.setVisible(true);
}
}
运行结果: