Java 中的按鈕組

Sheeraz Gul 2023年10月12日
Java 中的按鈕組

Java 中的按鈕組與單選按鈕一起使用,以確保只選擇一個單選按鈕。單選按鈕和按鈕組都屬於 Java 的 Swing 庫。

本教程演示如何在 Java 中使用按鈕組。

Java 中的按鈕組

Button group 用於在 Java 中建立一組單選按鈕,要建立按鈕組,我們使用以下方法和建構函式。

JRadioButton Radio_Button1 = new JRadioButton("Radio Button Group 1"); // Creates a new radio button

JRadioButton Radio_Button2 = new JRadioButton(
    "Radio Button Group 2", true); // Creates a radio button which is already selected

ButtonGroup Button_Group = new ButtonGroup(); // Creates new button group

Button_Group.add(Radio_Button1); // Add radio button to the button group

讓我們嘗試一個具有多個單選按鈕的按鈕組示例。

package delftstack;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class Button_Groups {
  public static void main(String[] args) {
    Create_Frame();
  }

  private static void Create_Frame() {
    JFrame Demo_Frame = new JFrame("Button Groups");
    Demo_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    CreateBG(Demo_Frame);
    Demo_Frame.setSize(400, 200);
    Demo_Frame.setLocationRelativeTo(null);
    Demo_Frame.setVisible(true);
  }

  private static void CreateBG(final JFrame Demo_Frame) {
    JPanel Demo_Panel = new JPanel();
    LayoutManager Panel_Layout = new FlowLayout();
    Demo_Panel.setLayout(Panel_Layout);

    JRadioButton Radio_Button1 = new JRadioButton("Radio Button Group 1");
    JRadioButton Radio_Button2 = new JRadioButton("Radio Button Group 2", true);
    JRadioButton Radio_Button3 = new JRadioButton("Radio Button Group 3");
    JRadioButton Radio_Button4 = new JRadioButton("Radio Button Group 4");

    ButtonGroup Button_Group = new ButtonGroup();
    Button_Group.add(Radio_Button1);
    Button_Group.add(Radio_Button2);
    Button_Group.add(Radio_Button3);
    Button_Group.add(Radio_Button4);

    Demo_Panel.add(Radio_Button1);
    Demo_Panel.add(Radio_Button2);
    Demo_Panel.add(Radio_Button3);
    Demo_Panel.add(Radio_Button4);
    Demo_Frame.getContentPane().add(Demo_Panel, BorderLayout.CENTER);
  }
}

上面的程式碼在一個按鈕組中建立了一個帶有四個單選按鈕的面板。請參閱下面動畫中的輸出。

按鈕組

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - Java GUI