使用 Swing 組件構建桌面計算器,包含 JTextField 顯示區、JButton 數字鍵與運算符鍵,採用 BorderLayout 與 GridLayout 佈局。核心邏輯在 ActionListener 中根據按鈕類型處理:數字鍵拼接顯示字串,運算符鍵記錄運算子並暫存運算數,等號鍵觸發計算並顯示結果。使用 DecimalFormat 格式化輸出,避免科學計數法。
public class Calculator extends JFrame {
private JTextField display;
private double result = 0;
private String operator = "";
public Calculator() {
// 佈局初始化、按鈕註冊監聽器
// 運算邏輯在 actionPerformed 中實現
}
private void calculate(double current) {
switch (operator) {
case "+": result += current; break;
case "-": result -= current; break;
case "*": result *= current; break;
case "/": result /= current; break;
}
display.setText(new DecimalFormat("0.##########").format(result));
}
}
完整代碼包含退位鍵、清除鍵、正負號切換等功能,展示了事件驅動程式設計與 Swing 佈局管理的綜合應用。