带有 JRadioButton r[]=new JRadioButton[3] 的 setSelected() 不起作用 [英] setSelected() with JRadioButton r[]=new JRadioButton[3] not working

查看:22
本文介绍了带有 JRadioButton r[]=new JRadioButton[3] 的 setSelected() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();
        }
    }

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

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.

推荐答案

你可以做buttonGroup.clearSelection().

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

but this method is available in java 1.6+ only.

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
        }

这篇关于带有 JRadioButton r[]=new JRadioButton[3] 的 setSelected() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆