Java 每次选择新项目时打印所选组合框项目

Java 每次选择新项目时打印所选组合框项目,java,javafx,combobox,Java,Javafx,Combobox,我在控制器类中有一个组合框: public class Controller { static String selectedCountry; @FXML private ResourceBundle resources; @FXML private URL location; @FXML private ComboBox<String> comboBoxCountries; @FXML void in

我在控制器类中有一个组合框:

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();

    }
}

只需将侦听器添加到selected item属性:

ComboxCountries.getSelectionModel().selectedItemProperty().addListener((可观察、旧值、新值)->{
System.out.println(newValue);
});

unrelated:不要对字段(或方法)使用静态作用域,您真正需要它的情况非常罕见(这里的用法当然不属于这些)。
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();
    }