首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java Swing 使用 JButton 陣列建構計算機介面完整範例

     編輯:Java 程式設計入門

程式功能

示範以二維陣列 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 持有元件引用,便於後續啟用/停用、樣式調整。
GridLayoutnew GridLayout(4,4,5,5) 固定 4×4,水平/垂直間距 5px,自動等寬高。
單一監聽器所有按鈕共用一個 Lambda ActionListener,透過 e.getSource() 取得按鈕文字,簡化程式碼。
BorderLayout視窗整體:北邊顯示欄、中間按鈕面板,擴展性佳。

延伸實作建議

  1. 運算邏輯:引入 ScriptEngineManager (JavaScript 引擎) 或自寫中序轉後序運算式評估器。
  2. 按鍵盤支援:為視窗加入 KeyListener 對應數字鍵、Enter、Backspace。
  3. 樣式美化:使用 UIManager 設定 LookAndFeel、按鈕邊框、背景色。
  4. 科學計算機擴充:增加 JToggleButton 切換度/弧度、函數鍵(sin、log 等),動態調整 GridLayout 行數。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved