2D JRadioButton object array

neomal :

I am creating a survey form using java swing. I'm loading questions and answers from my database to the view and I'm dynamically loading radio buttons (answers) to the view.

I created a 2D array to generate JRadioButton objects.

JRadioButton[][] rdbtnanswer;

public method() {
    int ans_yval = 0; 

    for (int i = 0; i < questions.getNumberOfQuestions(); i++) {

        String questionnair = questions.getQuestion(i);

        Vector<Answers> vector_answers = questions.getAnswer(questionnair);

        ButtonGroup group = new ButtonGroup();

         rdbtnanswer = new JRadioButton[questions.getNumberOfQuestions()][vector_answers.size()];

         for (int v = 0; v < vector_answers.size(); v++) {

            rdbtnanswer[i][v] = new JRadioButton(vector_answers.get(v).getAnswers());
            rdbtnanswer[i][v].setBounds(31, 170+ans_yval, 236, 23);
            contentPane.add(rdbtnanswer[i][v]); 
            group.add(rdbtnanswer[i][v]);

             ans_yval = ans_yval + 25; 
         }          
    }
}

I get the answers in the UI perfectly.

But when I create another inner, outer for loop and try to print the rdbtnanswer object values, values are not there. Each array replaced from last one. I need the reason for that.

c0der :

An mre demonstrating the problem (or the solution in this case) could be like so:

import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.JRadioButton;

class Main {

    private JRadioButton[][] rdbtnanswer;

    public static void main(String args[]) {
        new Main().method();
    }

    public void method() {

        int numberOfQuestions = 5; //questions.getNumberOfQuestions();
        rdbtnanswer = new JRadioButton[numberOfQuestions ][0];

        for (int i = 0; i < numberOfQuestions; i++) {
            Vector<String> vector_answers = getAnswer(i);
            JRadioButton[] rowOfButtons = new JRadioButton[vector_answers.size()];
             for (int v = 0; v < vector_answers.size(); v++) {
                 rowOfButtons[v] = new JRadioButton(vector_answers.get(v));
             }
             rdbtnanswer[i]= rowOfButtons;
        }

        //printout for testing 
        for(JRadioButton[] rowOfButtons : rdbtnanswer) {
            for(JRadioButton btn : rowOfButtons) {
                System.out.print(btn.getText()); //print row 
            }
            System.out.println();
        }
    }

    //create a vector of Strings with values "0", "1", ......."i" for testing
    private Vector<String> getAnswer(int i) {
        List<String> list = IntStream.range(0, i+1).boxed().map(String::valueOf).collect(Collectors.toList());
        return new Vector<>(list);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=317110&siteId=1