0

I have a ToggleGroup of buttons which can be 3 buttons with the togglename choose an answers or 2 buttons with the togglename true or false. As a matter of fact the togglegroup contains buttons which correspond to asnwers (from questions to a quiz game I made in javafx). On the click event I want to locate which buttons was pressed and returned the correspondant value during the actionlistener.

My code is the following:`

groupAnswerQ = new ToggleGroup();

class MyChooseAnswerButton extends ToggleButton {
     public MyChooseAnswerButton() {
        setToggleGroup(groupAnswerQ);
        setWrapText(true);
     }
}

SanswerButton1 = new MyChooseAnswerButton();
SanswerButton2 = new MyChooseAnswerButton();
SanswerButton3 = new MyChooseAnswerButton();

groupAnswerQ.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
  public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
     if (new_toggle != null) {
                textAnswerQ = (String) groupAnswerQ.getSelectedToggle().getUserData();
                System.out.println("textAnswerQ : " + textAnswerQ);
    }
  }
});`

This is for the case of choose an answer (for the true or false is the similar code). My problem is that when the event is detected the textAnswerQ returns always null even when the new_toggle is not null. What am I doing wrong here?

konstantin
  • 853
  • 4
  • 16
  • 50
  • 1
    Where do you set the UserData? – Felix Jun 08 '17 at 12:53
  • In my code in the main class I am initializing the buttons with setUserData. – konstantin Jun 08 '17 at 13:10
  • 1
    Why go through the trouble of creating the MyChooseAnswerButton class? Why not just create the buttons in your code the regular way? You probably need to post more code to get a good answer as to why you are having this problem. – SedJ601 Jun 08 '17 at 13:23
  • 2
    If `textAnswerQ` is null, then clearly the problem is that you haven't set the user data on the toggle buttons. If you think you are doing so, then clearly you're doing something wrong in that code. Create a [MCVE] and [edit] your question to include it. – James_D Jun 08 '17 at 13:24

1 Answers1

1

Reference here

Is there a reason you're checking if new_toggle is null? What's passed into the new_toggle variable? If there's no issue with your userData then try checking if groupAnswerQ.getSelectedToggle() is null.

kevinxia
  • 58
  • 6
  • The method will be invoked whenever the value held in selectedToggleProperty changes. The value may be null (no toggle selected) – Felix Jun 08 '17 at 13:02