编写一个程序,有一个标题为“简易计算器”的窗口,布局策略为FlowLayout布局。窗口内有4个按钮,分别为“+”、“_”、 “*”、“\”,另外,窗口中还有三个文本框。用户在两个文本框中输入两个运算数,单击相应的按钮,程序将两个文本框的数字做运算,在第三个框中显示结果。
注:考虑到文本框中输入的内容有非数字的可能性,要求程序处理NumberFormatExcxception异常(处理方式不限制)。
这种项目网上一大把
Java计算器:
package com.test.server;
import java.awt.Button;
import java.awt.Color;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Login extends JFrame implements ActionListener {
Button b1, b2, b3, b4;
JTextField text, text1, res;
public Login() {
super("计算器");
// 设置布局(设置没有布局,才能自己定位)
setLayout(null);
Label uname = new Label("操作数1:");
// 加入窗口中
add(uname);
// 设置组件位置 (组件的x坐标,组件的y坐标,组件的长,组件的高)
uname.setBounds(20, 50, 40, 20);
// 操作数1
text = new JTextField();
add(text);
text.setBounds(65, 50, 200, 20);
// 操作数2
Label pwd = new Label("操作数2:");
add(pwd);
pwd.setBounds(20, 80, 40, 20);
// 操作数2
text1 = new JTextField();
add(text1);
text1.setBounds(65, 80, 200, 20);
// 结果
Label rest = new Label("结果:");
add(rest);
rest.setBounds(20, 110, 40, 20);
// 结果
res = new JTextField();
add(res);
res.setBounds(65, 110, 200, 20);
// 按钮1
b1 = new Button("加法");
b1.setForeground(Color.red);
add(b1);
b1.setBounds(20, 140, 80, 30);
// 按钮2
b2 = new Button("减法");
b2.setForeground(Color.blue);
add(b2);
b2.setBounds(120, 140, 80, 30);
// 按钮2
b3 = new Button("乘法");
b1.setForeground(Color.green);
add(b3);
b3.setBounds(220, 140, 80, 30);
// 按钮2
b4 = new Button("除法");
b1.setForeground(Color.yellow);
add(b4);
b4.setBounds(320, 140, 80, 30);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
setSize(440, 250);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Login();
}
public void actionPerformed(ActionEvent e) {
float t1 = Float.parseFloat(text.getText());
float t2 = Float.parseFloat(text1.getText());
if(e.getSource()==b1){
res.setText((t1+t2)+"");
}else if(e.getSource()==b2){
res.setText((t1-t2)+"");
}else if(e.getSource()==b3){
res.setText((t1*t2)+"");
}else if(e.getSource()==b4){
res.setText((t1/t2)+"");
}
}
}