【问题标题】:How to add a radio button group in a core java program such that only one radio button is selected at one time?如何在核心java程序中添加一个单选按钮组,以便一次只选择一个单选按钮?
【发布时间】:2013-07-20 04:57:02
【问题描述】:

我正在用核心 java 构建一个项目。但是我坚持制作一个单选按钮组(用于输入性别(男性/女性)。为此,我需要一个单选按钮组,以便一次只选择一个单选按钮;并相应地将输入输入数据库。请帮忙。

【问题讨论】:

标签: java swing jradiobutton buttongroup


【解决方案1】:

请尝试使用 ButtonGroup 组件,并将两个名为 male 和 female 的 JRadioButton 组件添加到 ButtonGroup 对象,然后使用 setVisible(true) 将其显示在 JFrame 中;方法。

下面的代码应该很有用:-

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

public class Rb extends JFrame {
    Rb() {
        JRadioButton male = new JRadioButton("male");
        JRadioButton female = new JRadioButton("Female");
        ButtonGroup bG = new ButtonGroup();
        bG.add(male);
        bG.add(female);
        this.setSize(100, 200);
        this.setLayout(new FlowLayout());
        this.add(male);
        this.add(female);
        male.setSelected(true);
        this.setVisible(true);
    }

    public static void main(String args[]) {
        Rb j = new Rb();
    }
}

【讨论】:

    【解决方案2】:

    这是一个单选按钮分组:

    JRadioButton button1 = ...;
    button1.setSelected(true);
    JRadioButton button2 = ...;
    ButtonGroup group = new ButtonGroup();
    group.add(button1);
    group.add(button2);
    

    【讨论】:

    • 我试过这个东西。但它在运行时显示 NUllPOinterException。
    • @user2079152 异常堆栈跟踪会告诉您异常发生的确切位置。如果您无法理解,请在您的问题中发布您的代码和异常的完整堆栈跟踪。
    【解决方案3】:
        JPanel radioButtonPanel = new JPanel();
        append = new JRadioButton("append");
        build = new JRadioButton("x.x.1");
        build.setSelected(true); //sets this button as selected on startup
        small = new JRadioButton("x.1.x");
        huge = new JRadioButton("1.x.x");
    
        // Create the button group to keep only one selected.
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(append);
        btnGroup.add(build);
        btnGroup.add(small);
        btnGroup.add(huge);
    

    然后您将您的按钮添加到您的 JPanel 或类似的东西。

    【讨论】:

    • 我们需要创建一个 JPanel 还是直接将 JRadioButtons 添加到 JFrame 中?
    • 两者都应该是可能的,但最好使用:带有 1 个或多个 JPanel 的 JFrame。每个 JPanel 都有 1 个或多个其他组件,例如 RadioButtons、Buttons、TextFields 等。
    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 2017-06-28
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多