运行界面:
代码:
package com.sxpi;
import java.awt.Button;
public class WenDuChang extends JFrame implements ActionListener{
private JTextField textField;
private JTextField textField_1;
private JLabel label;
private JLabel label_1;
private JLabel label_2;
private JRadioButton[] radioButton;
private JButton button;
private JButton button_1;
private ButtonGroup bg;
public WenDuChang() {
//获取你的屏幕的宽和高
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
setLocation(width/2-200, height/2-150);
setTitle("\u6E29\u5EA6\u8F6C\u6362\u5668");
getContentPane().setLayout(null);
textField = new JTextField();//摄氏温度
textField.setText("0.0");
textField.setBounds(50, 63, 84, 27);
getContentPane().add(textField);
textField.setColumns(10);
label = new JLabel("\u6444\u6C0F\u6E29\u5EA6");
label.setBounds(137, 69, 54, 15);
getContentPane().add(label);
label_1 = new JLabel("=");
label_1.setBounds(201, 69, 54, 15);
getContentPane().add(label_1);
textField_1 = new JTextField();//华氏温度
textField_1.setText("0.0");
textField_1.setBounds(223, 66, 90, 24);
getContentPane().add(textField_1);
textField_1.setColumns(10);
label_2 = new JLabel("\u534E\u6C0F\u6E29\u5EA6");
label_2.setBounds(323, 69, 54, 15);
getContentPane().add(label_2);
radioButton = new JRadioButton[2];
radioButton[0] = new JRadioButton("\u6444\u6C0F\u8F6C\u534E\u6C0F",true);
radioButton[0].setBounds(100, 142, 121, 23);
getContentPane().add(radioButton[0]);
radioButton[1] = new JRadioButton("\u534E\u6C0F\u8F6C\u6444\u6C0F");
radioButton[1].setBounds(223, 142, 121, 23);
getContentPane().add(radioButton[1]);
bg=new ButtonGroup();
bg.add(radioButton[0]);
bg.add(radioButton[1]);
button = new JButton("\u6E29\u5EA6\u8F6C\u5316");
button.setBounds(100, 196, 93, 23);
button.addActionListener(this);
getContentPane().add(button);
button_1 = new JButton("\u9000\u51FA");
button_1.setBounds(237, 196, 93, 23);
button_1.addActionListener(this);
getContentPane().add(button_1);
setSize(450, 300);
setVisible(true);
}
//用于温度转换的方法-----业务处理
public String WenDuChang(final double tc,final double tf,boolean flag){
double wdc=0.0;
//小数格式化,引号中的0.000表示保留小数点后二位(第四位四舍五入)
DecimalFormat df = new DecimalFormat("0.00");
String str;
if(flag){
wdc=9*(tc-10)/5+50; //摄氏温度转化为华氏温度
}
else{
wdc=5*(tf-50)/9+10; //华氏温度转化为摄氏温度
}
str=df.format(wdc);
return str;
}
@Override
public void actionPerformed(ActionEvent e) {
double tc = Double.parseDouble(textField.getText().trim());
double tf = Double.parseDouble(textField_1.getText().trim());
if(e.getSource()==button){
//System.out.println("按钮被选中.....");
if(radioButton[0].isSelected()){//判断radioButton是否被选中
textField_1.setText(WenDuChang(tc,tf,true));
}
if(radioButton[1].isSelected()){
textField.setText(WenDuChang(tc,tf,false));
}
}
if(e.getSource()==button_1){
System.exit(0);
}
}
}