Asmita
Asmita

Reputation: 27

togglegroup.getSelectedToogle() always returns null JavaFX

I have this code to get the values from the selected ToggleGroup.

When I run this code however, I get an empty list back. I can't seem to figure out how to solve this.

   public TestPane(TestService service) {
        this.service = service;

        this.setPrefHeight(300);
        this.setPrefWidth(750);

        this.setPadding(new Insets(5, 5, 5, 5));
        this.setVgap(5);
        this.setHgap(5);

        questionField = new Label();
        vragen = service.getAllQuestions();
        Question question = vragen.iterator().next();
        questionField.setText(question.getQuestion());
        vragen.remove(question);

        add(questionField, 0, 0, 1, 1);

        statementGroup = new ToggleGroup();
        Set<String> statements = question.getStatements();
        System.out.println(statements);
        int i = 1;
        for (String st : statements) {
            radio = new RadioButton(st);
            radio.setText(st);
            radio.setUserData(st);
            radio.setToggleGroup((ToggleGroup) statementGroup.getUserData());
            add(radio, 0, i++);
        }

        submitButton = new Button("Submit");
        add(submitButton, 0, i);
        submitButton.setOnAction(new SubmitHandler(this,service));
    }

    public List<String> getSelectedStatements() {
        List<String> selected = new ArrayList<String>();
        if (statementGroup.getSelectedToggle() != null) {
            selected.add(statementGroup.getSelectedToggle().getUserData().toString());
        }
        return selected;
    }

Upvotes: 1

Views: 1289

Answers (1)

DVarga
DVarga

Reputation: 21799

The following line is incorrect:

radio.setToggleGroup((ToggleGroup) statementGroup.getUserData());

The correct call would be:

radio.setToggleGroup(statementGroup);

To answer the question "why": The getSelectedToggle method of the ToggleGroup returns null all the time, because there are no toggles associated with it, as

(ToggleGroup) statementGroup.getUserData()

returns null, therefore actually radio.setToggleGroup(null) will be executed, which means: the RadioButton has no toggle group.

Upvotes: 1

Related Questions