Search code examples
javajavafxcombobox

Print selected combo box item every time new item is selected


I have a comboBox in Controller class:

public class Controller {

    static String selectedCountry;

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private ComboBox<String> comboBoxCountries;

    @FXML
    void initialize() {
        assert comboBoxCountries != null : "fx:id=\"comboBoxCountries\" was not injected: check your FXML file 'app.fxml'.";

        comboBoxCountries.setItems(Main.COUNTRIES);

        selectedCountry = comboBoxCountries.getSelectionModel().getSelectedItem();

    }
}

In Main I'd like to print selected item in the console. What can I do to print a newly selected value every time new item is selected?

public class Main extends Application {
public static void main(String[] args) {
        launch(args);
 }

    @Override
    public void start(Stage stage) throws Exception {
        System.out.println(Controller.selectedCountry);
        Parent root= FXMLLoader.load(getClass().getResource("/fxml/app.fxml"));
        Scene scene = new Scene(root,1200,900);
        stage.setScene(scene);
        stage.show();
    }

Solution

  • Just add a listener to the selected item property:

    comboBoxCountries.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        System.out.println(newValue);
    });