gpt4 book ai didi

java - 每次选择新项目时打印选定的组合框项目

转载 作者:行者123 更新时间:2023-11-30 05:17:43 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com