1

I have 5 JRadio buttons on my swing application. When I click my Jradio button. I have created a joption dialogue to display that it is clicked. But when I unselect it it also displays that it is selected. What is the problem? One of my Jradio button coding.

      private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
{
      JOptionPane.showMessageDialog(null,"one is selected");
}

So I finally got answer

with help of @Neil Locketz

     private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) 
     {
        if(jRadioButton1.isSelected())
          {
            JOptionPane.showMessageDialog(null,"one is selected");
          }
     }

Thanks

Ameer
  • 600
  • 1
  • 12
  • 27

4 Answers4

2
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1 for digging up the issue. Though, it isn't virulent here because the OP is using an ActionListener, not an ItemListener. On the other hand: that's only coincidental - as there's no guarantee on listener notification sequence. So another (virtual :-) +1 for carefully thinking of invokeLater! – kleopatra Jan 31 '13 at 14:01
1

You need a reference to the JRadioButton Object so you can call button.isSelected() this will return a boolean of whether or not the button that you are testing is selected.

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34
0

Keep in mind this is totally pseudo-code

     JRadioButton testButton1=new JRadioButton("button1");
     JRadioButton testButton2=new JRadioButton("button2");

     ButtonGroup btngroup=new ButtonGroup();  

     btngroup.add(testButton1);  
     btngroup.add(testButton2);  

     boolean test;

     foreach(JRadioButton b in btngroup){
        test = b.isSelected();
        if(test)
           JOptionPane.showMessageDialog(null, b.getValue() + "is selected");
     }
0

I suggest you create one single ActionListener instance and add it to all your buttons. Something like this:

ButtonGroup group = new ButtonGroup();
JRadioButton radio = new JRadioButton("1");
JRadioButton radio2 = new JRadioButton("2");
JRadioButton radio3 = new JRadioButton("3");
group.add(radio);
group.add(radio2);
group.add(radio3);
ActionListener a = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JRadioButton source = (JRadioButton) e.getSource();
        System.out.println(source.getText() + " selected " + source.isSelected());
    }
};
radio.addActionListener(a);
radio2.addActionListener(a);
radio3.addActionListener(a);
Dan D.
  • 32,246
  • 5
  • 63
  • 79