开发者

Can I set a value to a radio button in Java?

It's possible 开发者_JAVA百科set a value to a radio in Java? If the radio is selected, I get the value of them.

EDIT: the value is some like: radio1 = value 10, radio2, value = 15, radio3 = value 30, etc, not if it is selected or not.


To select from code, you can use

 JRadioButton rb1 = new JRadioButton("Select Me");
 rb1.setSelected(true);

and to get selection

 boolean selected = rb1.isSelected();


To set a value:

JRadioButton rb = new JRadioButton(Integer.toString(10));

To get value of selected:

rb.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        System.out.println("Selected value = " +  e.getActionCommand());
    }
});

EDIT

If you have multiple radio buttons that perform the same action when selected, I'd suggest all of them register the same ActionListener:

private class MyActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e){
      System.out.println("Selected value = " +  e.getActionCommand());
    }
}

Reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜