createFrame 繼承無,直接管理 Frame、27 個 Button、兩個 TextField。setLayout(null)) 精確控制組件座標與大小。ButtonHandler 實作 ActionListener 處理所有按鈕事件。double op1, op2, op2x, op3; // 運算數、暫存值、結果
char op=0, opx=0, opp=0; // 當前運算符、上一運算符、等號前運算符
boolean b=false; // 是否已輸入小數點
boolean c=false; // 是否剛按過運算符(需清屏)
boolean firstdeng=true; // 首次按等號標記
double mjia=0; // 記憶體值
0.。c=true 時(剛按運算符),清屏顯示新數字並重置 c。b 標記。op2。=,先執行 calculateNow(op1, op, op2) 更新 op1(連續運算支援)。op1,置 c=true 等待下一操作數。op2x = op2(支援連續等號重複上次運算)。calculateNow(op1, op, op2x),顯示結果,標記 opp='='。BackSpace:刪除最後一字符。CE:清除當前輸入;C:全清狀態重置。+/-、1/x、sqrt、%:即時計算並更新顯示與 op2。MC/MR/MS/M+:操作 mjia,text2 顯示 M 指示器。private double calculateNow(double op1, char op, double op2) {
switch(op) {
case '+': return op1+op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': return op2==0? op1 : op1/op2; // 除零保護
case '%': return op2==0? op1 : op1%op2;
default: return op2;
}
}
public static void main(String[] args) { new createFrame().createWindow(); }
private void centershow(int w, int h, Frame f) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
f.setLocation((d.width-w)/2, (d.height-h)/2);
}
純 AWT 手寫計算器鍛鍊了事件驅動、狀態機設計、邊界條件處理(除零、小數點、連續運算),是 GUI 入門的經典實戰。