示範以二維陣列 JButton[][] 對應按鈕標籤矩陣,透過 GridLayout(4,4) 自動排版 16 個按鈕(數字 0-9、運算子 + - × ÷、小數點、等號),點擊按鈕將字元附加至頂部顯示欄(JTextField),僅實作 UI 佈局與事件綁定,不含實際運算邏輯。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorUI extends JFrame {
private final JTextField display = new JTextField();
public CalculatorUI() {
super("按鈕陣列計算機介面");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100, 100, 300, 320);
setLayout(new BorderLayout(10, 10));
// 顯示欄
display.setHorizontalAlignment(SwingConstants.RIGHT);
display.setPreferredSize(new Dimension(10, 50));
display.setFont(new Font("微軟正黑體", Font.PLAIN, 24));
add(display, BorderLayout.NORTH);
// 按鈕面板
JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
String[][] labels = {
{"1","2","3","+"},
{"4","5","6","-"},
{"7","8","9","×"},
{".","0","=","÷"}
};
JButton[][] buttons = new JButton[4][4];
ActionListener btnListener = e -> {
JButton src = (JButton) e.getSource();
display.setText(display.getText() + src.getText());
};
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
buttons[r][c] = new JButton(labels[r][c]);
buttons[r][c].setFont(new Font("微軟正黑體", Font.BOLD, 18));
buttons[r][c].addActionListener(btnListener);
panel.add(buttons[r][c]);
}
}
add(panel, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CalculatorUI::new);
}
}
| 技術 | 說明 |
|---|---|
| 二維陣列 | String[][] labels 定義介面矩陣,JButton[][] buttons 持有元件引用,便於後續啟用/停用、樣式調整。 |
| GridLayout | new GridLayout(4,4,5,5) 固定 4×4,水平/垂直間距 5px,自動等寬高。 |
| 單一監聽器 | 所有按鈕共用一個 Lambda ActionListener,透過 e.getSource() 取得按鈕文字,簡化程式碼。 |
| BorderLayout | 視窗整體:北邊顯示欄、中間按鈕面板,擴展性佳。 |
ScriptEngineManager (JavaScript 引擎) 或自寫中序轉後序運算式評估器。KeyListener 對應數字鍵、Enter、Backspace。UIManager 設定 LookAndFeel、按鈕邊框、背景色。JToggleButton 切換度/弧度、函數鍵(sin、log 等),動態調整 GridLayout 行數。