如何显示JRadio按钮处于选中状态和取消选中状态



我的挥杆应用程序上有 5 个 JRadio 按钮。当我点击我的Jradio按钮时。我创建了一个joption对话框来显示它已被单击。但是当我取消选择它时,它也会显示它已被选中。问题出在哪里?我的一个 Jradio 按钮编码。

      private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{
      JOptionPane.showMessageDialog(null,"one is selected");
}

所以我终于得到了答案

在@Neil洛克茨的帮助下

     private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {
        if(jRadioButton1.isSelected())
          {
            JOptionPane.showMessageDialog(null,"one is selected");
          }
     }

谢谢

  • 不能直接,必须包装,延迟此事件以显示内部JOptionPane invokeLater()

  • 这是 Java6 版本的错误 6924233 : JCheckBox itemListener 中的 JOptionPane 导致 setSelected(false)

  • 更多在我的(Similair???)问题中

您需要引用 JRadioButton 对象,以便可以调用 button.isSelected() 这将返回一个布尔值,表示您正在测试的按钮是否被选中。

我建议您创建一个ActionListener实例并将其添加到所有按钮中。像这样:

ButtonGroup group = new ButtonGroup();
JRadioButton radio = new JRadioButton("1");
JRadioButton radio2 = new JRadioButton("2");
JRadioButton radio3 = new JRadioButton("3");
group.add(radio);
group.add(radio2);
group.add(radio3);
ActionListener a = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JRadioButton source = (JRadioButton) e.getSource();
        System.out.println(source.getText() + " selected " + source.isSelected());
    }
};
radio.addActionListener(a);
radio2.addActionListener(a);
radio3.addActionListener(a);
请记住,

这完全是伪代码

     JRadioButton testButton1=new JRadioButton("button1");
     JRadioButton testButton2=new JRadioButton("button2");
     ButtonGroup btngroup=new ButtonGroup();  
     btngroup.add(testButton1);  
     btngroup.add(testButton2);  
     boolean test;
     foreach(JRadioButton b in btngroup){
        test = b.isSelected();
        if(test)
           JOptionPane.showMessageDialog(null, b.getValue() + "is selected");
     }

最新更新