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

Java Swing 組件完全指南:JButton、JCheckBox、JRadioButton 實戰詳解

     編輯:Java 綜合教學

前言

Swing 是 Java GUI 開發的基礎框架,按鈕組件是交互的核心。本文系統講解 JButton(提交按鈕)、JCheckBox(復選框)、JRadioButton(單選按鈕)的創建、屬性配置、事件處理與佈局實戰。

一、JButton:提交按鈕

1.1 四大構造方法

JButton()JButton(String text)JButton(Icon icon)JButton(String text, Icon icon)
構造方法說明
無文本無圖標
指定文本
指定圖標
同時指定文本和圖標

1.2 關鍵屬性設置方法

  • setIcon(Icon) / setPressedIcon() / setRolloverIcon():不同狀態圖標
  • setToolTipText(String):懸停提示
  • setBorderPainted(boolean):是否繪製邊框
  • setContentAreaFilled(boolean):是否填充內容區
  • setFocusPainted(boolean):是否繪製焦點框
  • setEnabled(boolean):啟用/禁用
  • setMnemonic(int):快捷鍵

1.3 完整示例:圖文混排、狀態控制、事件響應

public class JButtonDemo extends JFrame {
    public JButtonDemo() {
        // 1. 獲取圖片資源(放在 classpath 下)
        URL imgUrl = JButtonDemo.class.getResource("/images/button.jpg");
        Icon icon = new ImageIcon(imgUrl);

        // 2. 佈局:3行2列,間隙5
        setLayout(new GridLayout(3, 2, 5, 5));
        Container container = getContentPane();

        // 3. 批量創建按鈕,偶數禁用
        for (int i = 0; i < 5; i++) {
            JButton btn = new JButton("Button " + i, icon);
            if (i % 2 == 0) btn.setEnabled(false);
            container.add(btn);
        }

        // 4. 進階按鈕:純圖標、無邊框、提示、點擊彈窗
        JButton advancedBtn = new JButton();
        advancedBtn.setIcon(icon);
        advancedBtn.setBorderPainted(false);
        advancedBtn.setToolTipText("這是純圖標按鈕");
        advancedBtn.setPreferredSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
        advancedBtn.addActionListener(e -> 
            JOptionPane.showMessageDialog(this, "點擊觸發!"));
        container.add(advancedBtn);

        // 窗口設置
        setTitle("JButton 綜合演示");
        setSize(500, 550);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(JButtonDemo::new);
    }
}

運行效果1 運行效果2

二、JCheckBox:復選框

2.1 特點

  • 方形圖標 + 描述文本
  • 每個獨立保持「選中/未選中」狀態
  • 適合「多選」場景

2.2 事件監聽:ActionListener

public class CheckBoxDemo extends JFrame {
    private JTextArea logArea = new JTextArea(20, 50);

    public CheckBoxDemo() {
        setLayout(new BorderLayout());
        
        // 北部:日誌區域 + 滾動條
        JScrollPane scrollPane = new JScrollPane(logArea);
        add(scrollPane, BorderLayout.NORTH);

        // 南部:三個復選框
        JPanel panel = new JPanel();
        JCheckBox cb1 = new JCheckBox("選項 1");
        JCheckBox cb2 = new JCheckBox("選項 2");
        JCheckBox cb3 = new JCheckBox("選項 3");
        
        panel.add(cb1); panel.add(cb2); panel.add(cb3);
        add(panel, BorderLayout.SOUTH);

        // 統一監聽器
        ActionListener listener = e -> {
            JCheckBox source = (JCheckBox) e.getSource();
            logArea.append(source.getText() + " : " + (source.isSelected() ? "選中" : "取消") + "\n");
        };
        cb1.addActionListener(listener);
        cb2.addActionListener(listener);
        cb3.addActionListener(listener);

        setTitle("JCheckBox 事件演示");
        setSize(600, 650);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

復選框效果

三、JRadioButton:單選按鈕

3.1 核心規則

  • 圓形圖標,互斥選擇
  • 必須 加入 ButtonGroup 實現互斥
  • 同組中任一時刻僅有一個被選中

3.2 基礎示例

public class RadioButtonDemo extends JFrame {
    public RadioButtonDemo() {
        ButtonGroup group = new ButtonGroup();
        JPanel panel = new JPanel();

        JRadioButton rb1 = new JRadioButton("選項 A");
        JRadioButton rb2 = new JRadioButton("選項 B");
        JRadioButton rb3 = new JRadioButton("選項 C");

        group.add(rb1); group.add(rb2); group.add(rb3);
        panel.add(rb1); panel.add(rb2); panel.add(rb3);

        add(panel);
        setTitle("JRadioButton 基礎演示");
        setSize(200, 150);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

單選按鈕效果

四、綜合實戰:表單組合

public class FormDemo extends JFrame {
    public FormDemo() {
        setLayout(new GridLayout(3, 1));
        Container cp = getContentPane();

        // 第1行:愛好(多選)
        JPanel p1 = new JPanel();
        p1.add(new JLabel("愛好:"));
        p1.add(new JCheckBox("籃球"));
        p1.add(new JCheckBox("足球"));
        p1.add(new JCheckBox("排球"));
        cp.add(p1);

        // 第2行:性別(單選)
        JPanel p2 = new JPanel();
        ButtonGroup genderGroup = new ButtonGroup();
        JRadioButton male = new JRadioButton("男");
        JRadioButton female = new JRadioButton("女");
        genderGroup.add(male); genderGroup.add(female);
        p2.add(new JLabel("性別:"));
        p2.add(male); p2.add(female);
        cp.add(p2);

        // 第3行:按鈕
        JPanel p3 = new JPanel();
        p3.add(new JButton("提交"));
        p3.add(new JButton("重置"));
        cp.add(p3);

        setTitle("綜合表單演示");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

綜合表單效果

五、最佳實踐總結

組件適用場景關鍵點
JButton觸發動作(提交、取消、導航)圖標狀態分離、ToolTip、Mnemonic
JCheckBox獨立開關、多選項isSelected() 獲取狀態、ActionListener 監聽
JRadioButton互斥單選(性別、支付方式)必須配合 ButtonGroup、預設選中 setSelected(true)

六、現代化建議

  • 新項目優先考慮 **JavaFX**(更豐富的 UI、CSS 樣式、FXML 分離)。
  • 維護舊 Swing 項目時:統一使用 SwingUtilities.invokeLater() 啟動 EDT,避免線程安全問題。
  • 佈局管理器推薦 MigLayout(第三方)或 GroupLayout,避免絕對定位。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved