展开全部
效果图如下32313133353236313431303231363533e59b9ee7ad9431333363386166
参考代码如下import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AddFrame extends JFrame implements ActionListener {
JTextField jtf1, jtf2, jtf3;//文本框
JButton jbAdd, jbClear;//按钮
String defNum = "0.0"; //默认值
public AddFrame() {
//jp1 显示加法算式用
JPanel jp1 = new JPanel();
jtf1 = new JTextField(8);
JLabel jl1 = new JLabel("+");
jtf2 = new JTextField(8);
JLabel jl2 = new JLabel("=");
jtf3 = new JTextField(8);
jtf3.setEditable(false);//结果文本框,禁止编辑
jp1.add(jtf1);
jp1.add(jl1);
jp1.add(jtf2);
jp1.add(jl2);
jp1.add(jtf3);
clearText();//设置文本默认值
//jp2用于显示按钮
JPanel jp2 = new JPanel();
jbAdd = new JButton("相加");
jbAdd.addActionListener(this);
jbClear = new JButton("清空");
jbClear.addActionListener(this);
jp2.add(jbAdd);
jp2.add(jbClear);
add(jp1);
add(jp2);
setLayout(new GridLayout(2, 1));//布局,2行1列
setTitle("加法计算器");// 标题
setSize(360, 128);// 窗口大小
setLocationRelativeTo(null);// 窗口居中
setResizable(false);// 窗口禁止缩放
setDefaultCloseOperation(EXIT_ON_CLOSE);// 窗口点击关闭时,退出程序
}
public static void main(String[] args) {
new AddFrame().setVisible(true);// 创建窗口实例并可见
}
private void clearText() {//设置文字为初始化的0.0
jtf1.setText(defNum);
jtf2.setText(defNum);
jtf3.setText(defNum);
}
@Override
public void actionPerformed(ActionEvent e) {
//如果点击的是相加按钮.
if (e.getSource() == jbAdd) {
double d1, d2 = 0;
try {
d1 = Double.parseDouble(jtf1.getText().trim());//从文字到数字的转换
d2 = Double.parseDouble(jtf2.getText().trim());
} catch (Exception ex) {
jtf3.setText(defNum);
JOptionPane.showMessageDialog(null, "Sorry!不能输入字母汉字等.\n请输入合法的数字.", "错误提示", JOptionPane.ERROR_MESSAGE);
return;
}
jtf3.setText((d1 + d2) + "");
} else if (e.getSource() == jbClear) {//如果点击的时清空按钮
clearText();
}
}
}