1. 程式人生 > 其它 >使用Java製作簡易計算器

使用Java製作簡易計算器

import org.w3c.dom.Text;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//製作簡易計算器
public class TestCalculator {
public static void main(String[] args) {
// 啟動程式
new Calculator();
}
}
class Calculator{

public Calculator(){
//組合高於繼承 能使用new包含進來的儘量用new,降低耦合度 Frame frame = new Frame()
// 也是一種重要的程式設計思想!
Frame frame = new Frame();
// 建立文字框並設定列長
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(20);
Label label = new Label("+");
Button button = new Button("=");
//流式佈局
frame.setLayout(new FlowLayout());
frame.add(num1);
frame.add(label);
frame.add(num2);
frame.add(button);
frame.add(num3);
frame.pack();
frame.setVisible(true);
//使用匿名內部類監聽視窗,用於關閉視窗
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//給按鈕新增監聽 用於觸發事件,同時將文字框內容傳參到MyActionListener類
button.addActionListener(new MyActionListener1(num1,num2, num3));

}

}
class MyActionListener1 implements ActionListener {

private TextField num1,num2,num3;

public MyActionListener1(TextField num1, TextField num2,TextField num3){
this.num1=num1;
this.num2=num2;
this.num3=num3;
}
// 點選按鈕後計算結果
@Override
public void actionPerformed(ActionEvent actionEvent) {
// 獲取加數和被加數
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
//計算結果顯示於計算框
num3.setText(""+(n1+n2));
//將加數 被加數清空
num2.setText("");
num1.setText("");
}
}

效果圖