java编写计算器
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 计算器
*/
public class TestJsq {
public static void main(String[] args) {
MyFrame2 frame2 = new MyFrame2();
WindowClose.close(frame2);
}
}
//Frame
class MyFrame2 extends Frame {
TextField num1;
TextField num2;
TextField num3;
public MyFrame2(){
//创建文本框对象
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
//创建按钮对象
Button button = new Button("=");
//监听按钮事件
button.addActionListener(new MyListener());
//添加标签对象
Label label = new Label("+");
add(num1);
add(label);
add(num2);
add(button);
add(num3);
//流水排列
setLayout(new FlowLayout());
//setBounds(200,200,500,500);
//自适应
pack();
//可视化
setVisible(true);
}
//监听内部类
private class MyListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//获取文本内容,并强转为Integer类型,方便计算
Integer n1 = Integer.parseInt(num1.getText());
Integer n2 = Integer.parseInt(num2.getText());
//将计算结果写入到文本框
num3.setText(""+(n1+n2));
//将运行完的文本框置为空
num1.setText("");
num2.setText("");
}
}
}