Search code examples
jframejbuttonjtextfieldjradiobutton

How to make jbutton sum up the values of my jradiobuttons


I'm making a project in jFrame. It has 15 jRadiobuttons. What I want is a jButton to add the selected jRadioButtons and display the sum in a jTextField. Can anyone help me? I've been doing this for 3 days and cant get it right.


Solution

  • So you have numbers as values of the radiobuttons? Then try it like this: When the button is clicked, go through a foreach loop of all radiobuttons. in the loop, check if they are selected. If they are, you add their value to the Sum.

    Is that what you were asking for?

    EDIT

    1. You create A List containing all radiobuttons.
    2. In the Listener of the Button you write:

      int sum = 0;
      //foreach loop
      for (jRadiobutton rbutton : rbuttons){
        //Check if the button is selected
        if (rbutton.isSelected){
          sum += rbutton.Value;
        }
      }
      

    I hope this is good enough explained. Maybe the Syntax isn't correct, i haven't used java for a while now...