使用 Java AWT 元件建立桌面計算機,支援四則運算、開平方、連續運算、除零錯誤處理。採用事件驅動模型,介面佈局使用 GridLayout 與 FlowLayout 組合。
public class Counter extends Frame implements ActionListener {
// 輸入顯示區
TextField display = new TextField("", 15);
// 數字鍵盤 0-9
Button[] numButtons = new Button[10];
// 運算子按鈕
Button btnAdd, btnSub, btnMul, btnDiv, btnEq, btnPoint;
// 功能按鈕
Button btnSqrt, btnClear;
// 狀態變數
String operand1 = "", operand2 = "";
String operator = null;
boolean firstInput = true;
int opCount = 0;
double result = 0;
boolean error = false;
}
Counter()TextFieldGridLayout(4,4) 排列 0-9、小數點、四則運算、等號FlowLayout 排列開平方、清空// 數字鍵與小數點
for (Button b : numButtons) {
b.setActionCommand("number");
b.addActionListener(this);
}
btnPoint.setActionCommand("number");
// 運算子
for (Button b : new Button[]{btnAdd, btnSub, btnMul, btnDiv}) {
b.setActionCommand("oper");
b.addActionListener(this);
}
// 功能鍵
btnSqrt.addActionListener(this); // command="開平方"
btnClear.addActionListener(this); // command="清空"
btnEq.addActionListener(this); // command="="
actionPerformed()if ("number".equals(cmd)) {
if (firstInput) {
operand1 += label;
display.setText(operand1);
} else {
operand2 += label;
display.setText(operand2);
}
}
else if ("oper".equals(cmd)) {
if (operand1.isEmpty()) { reset(); return; }
opCount++;
if (opCount > 1) calculate(); // 連續運算:先算出前一結果
operator = label;
firstInput = false;
}
operand1 開根號,不需第二運算元operand1 供後續連續運算calculate()private void calculate() {
double n1 = Double.parseDouble(operand1);
double n2 = Double.parseDouble(operand2);
switch (operator) {
case "+": result = n1 + n2; break;
case "-": result = n1 - n2; break;
case "*": result = n1 * n2; break;
case "/":
if (n2 == 0) { error = true; return; }
result = n1 / n2; break;
}
if (error) display.setText("error");
else {
display.setText(String.valueOf(result));
operand1 = String.valueOf(result);
operand2 = "";
}
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
| 方向 | 說明 |
|---|---|
| Swing 遷移 | 改用 JFrame/JButton/JTextField,支援外觀主題 |
| 鍵盤支援 | 實作 KeyListener,對應數字鍵、Enter、Esc、Backspace |
| 科學運算 | 加入 sin/cos/log/指數等功能鍵 |
| 歷史記錄 | TextArea 顯示運算歷程 |
| 模式切換 | 標準/程式設計師/統計模式切換 |
import java.awt.*;
import java.awt.event.*;
public class Counter extends Frame implements ActionListener {
// ... 欄位宣告 ...
public Counter() { /* 介面建構 */ }
public void actionPerformed(ActionEvent e) { /* 事件分派 */ }
private void calculate() { /* 運算邏輯 */ }
public static void main(String[] args) {
new Counter(); // 啟動
}
}
這個計算機範例展示了 AWT 事件驅動程式設計的核心模式:狀態機管理輸入流程、ActionCommand 分派邏輯、介面與業務分離。雖然 AWT 已非主流,但其事件模型為 Swing/JavaFX 奠定基礎,理解此架構有助於掌握現代 GUI 框架精髓。