2

Currently I'm getting the selected button in this way, but I don't if this is the right/best method. MAybe there something more easy or object oriented than this.

private int getFilterType(JRadioButton... buttons) {
    for (int i = 0, n = buttons.length; i < n; i++) {
        if (buttons[i].isSelected()) {
            return i + 1;
        }
    }
    return buttons.length + 1;
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199

6 Answers6

4

I like using the ButtonGroup itself for this. i.e.,

import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

public class ButtonModelEg {
   public static final String[] BUTTON_TEXTS = {"Fe", "Fi", "Fo", "Fum"};

   private static void createAndShowUI() {
      final ButtonGroup btnGroup = new ButtonGroup();

      JPanel panel = new JPanel(new GridLayout(0, 1));
      for (String btnText : BUTTON_TEXTS) {
         JRadioButton radioBtn = new JRadioButton(btnText);
         radioBtn.setActionCommand(btnText);
         btnGroup.add(radioBtn);
         panel.add(radioBtn);
      }

      final JTextField selectionField = new JTextField();

      JButton button = new JButton(new AbstractAction("Get Choice"){
         public void actionPerformed(ActionEvent arg0) {
            // get the button model selected from the button group
            ButtonModel selectedModel = btnGroup.getSelection();
            if (selectedModel != null) {
               // and dislay it
               selectionField.setText(selectedModel.getActionCommand());
            }
         }
      });

      panel.add(button);
      panel.add(selectionField);

      JFrame frame = new JFrame("ButtonModelEg");
      frame.getContentPane().add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3

What you can do is to use a ButtonGroup (doc here) to which you add all the JRadioButton. The group will take care of managing the mutual exclusion of the button as well as providing you the getSelection() method which returns the underlying model of the radio button pressed. Then you can find an easy way to distinguish between the various models (maybe you can retrieve the parent of the model or use the setActionCommand and getActionCommand like in:

JRadioButton button1 = new JRadioButton(..);
button1.getModel().setActionCommand("MY_ACTION");

and then you can easily understand which one it is..

Jack
  • 131,802
  • 30
  • 241
  • 343
  • yup, my thoughts exactly! 1+ – Hovercraft Full Of Eels May 22 '11 at 15:25
  • 1+ for getting rid of the for loop. Still I haven't found a way to recover the JRadioButton itself without either looping through the ButtonGroup elements enumeration or resorting to some monkey business such as keeping an ActionCommand -> JRadioButton Map. Any idea on how to achieve that in a cleaner way? – Anthony Accioly May 22 '11 at 15:43
  • Why do you need the button instance itself? To know which one it is by an identifier is not enough for your purpose? It seems you need to know which kind of filter is applied so I don't understand why you need the specific object instance, could you clarify it? – Jack May 22 '11 at 15:47
  • I'm not the OP lol, I think it is more than enough for his purposes. And Camickr just solved my problems as well. – Anthony Accioly May 22 '11 at 15:53
2

You can use Darryl's Select Button Group which extend ButtonGroup to give you easy access to the radio button.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • That's exactly what I was looking for. The `getSelectedIndex` and `getSelectedButton` does the trick. Now I just need to improve them with some generics support so that I don't need to cast the `AbstractButton`and it is perfect. – Anthony Accioly May 22 '11 at 15:49
  • +1 from me - camickr is a true authority on all things Java and Swing, on both the Sun Java forums and here as well. – duffymo May 22 '11 at 16:22
  • @duffymo, Thanks, but I can't take credit for this as its Darryl's suggestion and code. As to being an authority, I'm not sure about that. I'm amazed at the knowledge of the memebers on all forums. I try to learn from their answers. – camickr May 22 '11 at 16:35
1

If you have to know which button was pushed, I'd say it's best to give it an individual listener. No worries then.

public class ListenerDemo
{
    private JButton button1;
    private JButton button2;

    public ListenerDemo(ActionListener listener1, ActionListener listener2)
    {
        this.button1 = new JButton("Button 1 Label");
        this.button.addActionListener(listener1);
        this.button2 = new JButton("Button 2 Label");
        this.button.addActionListener(listener2);

    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

Use ButtonGroup. The good thing about using the button group is that it takes care of things such as togglig between radio buttons for you, so that you don't have to worry about it.

You add your buttons to the group like so:

JRadioButton carrots = new JRadioButton("Carrots");
carrots.setActionCommand("carrots");

JRadioButton peas = new JRadioButton("Peas");
peas.setActionCommand("peas");

ButtonGroup group = new ButtonGroup();
group.add(carrots);
group.add(peas);

and when you need to get the selected button, you just use

group.getSelection();

You can also add listeners to each button, as shown in this example.

Mia Clarke
  • 8,134
  • 3
  • 49
  • 62
  • Just a quick note: [getSelection](http://download.oracle.com/javase/6/docs/api/javax/swing/ButtonGroup.html#getSelection()) returns a [ButtonModel](http://download.oracle.com/javase/6/docs/api/javax/swing/ButtonModel.html). To determine which JRadioButton is selected you need to either set its action command beforehand or loop through `ButtonGroup` elements enumeration as pointed in my answer. – Anthony Accioly May 22 '11 at 15:32
  • @Anthony Thanks for pointing that out. I've edited my answer to fix this. – Mia Clarke May 22 '11 at 16:10
0

I don't know if there is a way to get rid of the for loop. But at least you can use the ButtonGroup to dump the var-args. See an example here.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118