チェックボックスが選択されているかどうか Java で判断の方法

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()の返り値に基づいて適切なメッセージを出力します。

bannerAds