Search code examples
javajavafxfxml

Read out if RadioButton is selected in other controller


I am currently working on JavaFX Project where i need to access an FXML Object from another class to show a ComboBox if the RadioButton is selected.

So for example I have 4 RadioButtons called

//First Controller
@FXML
private RadioButton radioButtonS1, radioButtonS2, radioButtonS3, radioButtonS4;

I have to read them out in the other Controller to set them visible my ComboBoxes are called:

//Second Controller
@FXML
private ComboBox comboS1A, comboS1E1, comboS1E2;

@FXML
private ComboBox comboS2A, comboS2E1, comboS2E2;

@FXML
private ComboBox comboS3A, comboS3E1, comboS3E2;

@FXML
private ComboBox comboS4A, comboS4E1, comboS4E2;

So how can I see in the SecondController which RadioButton is selected in the FirstController and make the CombBox visible?

Thanks.


Solution

  • You can create a static int variable, and this variable will contain the selected RadioButton number

    public static int selectedCombo = -1;
    

    and put these lines in the initialize method of the first controller

    radioButtonS1.setOnAction(e->{
           selectedCombo = 0;
    });
    
    radioButtonS2.setOnAction(e->{
       selectedCombo = 1;
    });
    ...
    

    In the second controller, you need to add a switch statement like the following:

    switch(selectedCombo) {
    case 0: 
    // make the 1st comboBox visible
    break;
    case 1: 
    // make the 2nd comboBox visible
    break;
    ...
    }