简体   繁体   中英

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

It's possible 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM