温馨提示×

java怎么判断单选框是否选中

小亿
95
2023-12-08 10:37:45
栏目: 编程语言

在Java中,可以使用isSelected()方法来判断单选框是否被选中。

以下是一个示例代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonExample extends JFrame implements ActionListener {
    JRadioButton radioButton;
    JButton button;

    public RadioButtonExample() {
        setTitle("单选框示例");
        setSize(300, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        radioButton = new JRadioButton("选项");
        button = new JButton("判断选中");
        button.addActionListener(this);

        JPanel panel = new JPanel();
        panel.add(radioButton);
        panel.add(button);
        add(panel);

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (radioButton.isSelected()) {
            System.out.println("单选框选中");
        } else {
            System.out.println("单选框未选中");
        }
    }

    public static void main(String[] args) {
        new RadioButtonExample();
    }
}

在上述代码中,使用isSelected()方法来判断单选框是否选中。在actionPerformed(ActionEvent e)方法中,根据isSelected()的返回值来输出相应的信息。

0