Java 中的按钮组

Sheeraz Gul 2022年4月22日
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.JRadioButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

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);
   }
}

上面的代码在一个按钮组中创建了一个带有四个单选按钮的面板。请参阅下面动画中的输出。

按钮组

Author: 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