每次选择新项目时打印选定的组合框项目
Print selected combo box item every time new item is selected
我在 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();
}
}
在 Main 中,我想在控制台中打印选定的项目。每次选择新项目时如何打印新选择的值?
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();
}
只需为所选项目添加一个侦听器属性:
comboBoxCountries.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
System.out.println(newValue);
});
我在 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();
}
}
在 Main 中,我想在控制台中打印选定的项目。每次选择新项目时如何打印新选择的值?
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();
}
只需为所选项目添加一个侦听器属性:
comboBoxCountries.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
System.out.println(newValue);
});