hari dran
hari dran

Reputation: 115

How to do jButtongroup use to select radiobutton using java

i am create simple rating system in java. we have 5 radio button for rating the course.i attached screen shot image below.i have group buttonGroup1,buttonGroup2,buttonGroup3

enter image description here

i have do code in below. what i tried so far. first i tried with buttonGroup1 but i got the error was method isSelected in class ButtonGroup cannot ne applied to given types requird Button Model . how to write the code here properly and get it.

 if(buttonGroup1.isSelected())
        {
            
            if(r1.isSelected()){  
             
            JOptionPane.showMessageDialog(this,"1");    
          }  
             else if(r2.isSelected()){  
             
            JOptionPane.showMessageDialog(this,"2");    
          }  
             else if(r3.isSelected()){  
             
            JOptionPane.showMessageDialog(this,"3");    
          }  
             else if(r4.isSelected()){  
             
            JOptionPane.showMessageDialog(this,"4");    
          }  
            
             else if(r5.isSelected()){  
             
            JOptionPane.showMessageDialog(this,"5");    
          }  
           
        }

if(buttonGroup1.isSelected()) this line go the error method isSelected in class ButtonGroup cannot ne applied to given types requird Button Model .

Upvotes: 0

Views: 203

Answers (2)

maloomeister
maloomeister

Reputation: 2486

buttonGroup.isSelected(ButtonModel m) is not really what you want here, because this checks if a particular ButtonModel is selected. Either, you omit the whole outer if statement and just check all single radio buttons for selection, or you can use getSelection() and check for null.

Example:

if (buttonGroup1.getSelection() != null) {

    if (r1.isSelected()) {
        JOptionPane.showMessageDialog(this, "1");
    } else if (r2.isSelected()) {
        JOptionPane.showMessageDialog(this, "2");
    } else if (r3.isSelected()) {
        JOptionPane.showMessageDialog(this, "3");
    } else if (r4.isSelected()) {
        JOptionPane.showMessageDialog(this, "4");
    } else if (r5.isSelected()) {
        JOptionPane.showMessageDialog(this, "5");
    }
}

Upvotes: 1

Alex Rmcf
Alex Rmcf

Reputation: 924

From ButtonGroup documentation:

method isSelected(ButtonModel m) - Returns whether a ButtonModel is selected.

So to use that method you suppose to pass ButtonModel object there

Upvotes: 0

Related Questions