我在 Controller 类中有一个组合框:
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);
});
关于java - 每次选择新项目时打印选定的组合框项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60115092/