我在Controller类中有一个comboBox:
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();
}
答案 0 :(得分:1)
只需将侦听器添加到选定的item属性:
comboBoxCountries.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
System.out.println(newValue);
});