java 带有 JRadioButton r[]=new JRadioButton[3] 的 setSelected() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16699339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:42:34  来源:igfitidea点击:

setSelected() with JRadioButton r[]=new JRadioButton[3] not working

javaswing

提问by Salil Dua

Here I made a dummy Programme....

在这里我做了一个虚拟程序......

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
  class MyClass1 implements ActionListener
  {
JFrame fr;
JRadioButton opt[]=new JRadioButton[2];
JButton btnext;
JRadioButton r1;
MyClass1()
{
    fr=new JFrame();
    fr.setLayout(null);
    opt[0]=new JRadioButton("Hello");
    opt[1]=new JRadioButton("Welcome");
    r1=new JRadioButton("Jealsous");
    btnext=new JButton();
    ButtonGroup bg=new ButtonGroup();
    bg.add(opt[0]);
    bg.add(opt[1]);
    opt[0].setBounds(50,100,200,30);
    r1.setBounds(50,200,200,30);
    opt[1].setBounds(50,150,200,30);
    btnext.setBounds(400,350,100,30);
    fr.add(opt[1]);
    fr.add(opt[0]);
    fr.add(btnext);
    fr.add(r1);
    btnext.addActionListener(this);
    fr.setSize(800,500);
    fr.setVisible(true);
}
 public void actionPerformed(ActionEvent e)
        {
            System.out.println(opt[0].getText());
            opt[0].setSelected(false); //not working
            r1.setSelected(false);  //working
        }
    public static void main(String[] s)
        {
            new MyClass1();
        }
    }

In this code when I am clicking on button the radiobutton which is an array opt[0] is still selected. Whereas radiobutton r1 is not selected . So basically when I am calling the function setSelected with array of objects it is doing nothing, when me calling with distinct object it is working fine. In the big programme I need of array of objects so that I can use it in for loop and get it initialized to some value coming out of String 2Dimensional Array.

在这段代码中,当我单击按钮时,仍然选择了数组 opt[0] 的单选按钮。而单选按钮 r1 未被选中。所以基本上当我用对象数组调用函数 setSelected 时它什么都不做,当我用不同的对象调用它时它工作正常。在大程序中,我需要对象数组,以便我可以在 for 循环中使用它并将其初始化为来自 String 2Dimensional Array 的某个值。

回答by Ashish

You can do buttonGroup.clearSelection().

你可以做到buttonGroup.clearSelection()

but this method is available in java 1.6+ only.

但此方法仅在 java 1.6+ 中可用。

http://java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html#clearSelection()

http://java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html#clearSelection()

@Override
 public void actionPerformed(ActionEvent e)
        {
            System.out.println(opt[0].getText());
            bg.clearSelection();
            r1.setSelected(false);  //working
        }