问题
I have class:
public class Element {
private final IntegerProperty id;
private final StringProperty name;
...constructors...
public Integer getId() {
return id.get();
}
public void setId(Integer id) {
this.id.set(id);
}
public IntegerProperty idProperty() {
return id;
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
@Override
public String toString() {
return name.get();
}
And I try to display List of those elements in ComboBox. In my controller I have:
@FXML
private ComboBox<Element> combo;
And then I have following code in function that fill other GUI elements:
ObservableList<Element> elements = FXCollections.observableArrayList(ElRep.getElements());
combo = new ComboBox<Element>(elements);
combo.getSelectionModel().selectFirst();
I also tried:
combo.setItems(elements);
and nothing seems to work. I get empty ComboBox.
回答1:
You should never initialize fields annotated @FXML
: the point of that annotation is that the object is created as part of loading the FXML file and is injected into the controller. If you create a new object, you will no longer be referencing the object created by the FXML loader (and displayed in the UI): so any changes you make to that object's properties will not appear in the UI.
So omit the call to new ComboBox<>(...)
and use combo.setItems(...)
(or combo.getItems().setAll(...)
) to initialize the existing combo box:
Example controller:
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
public class Controller {
@FXML
private ComboBox<Element> combo ;
public void initialize() {
ObservableList<Element> elements = FXCollections.observableArrayList(
new Element(1, "Element 1"),
new Element(2, "Element 2")
);
combo.setItems(elements);
combo.getSelectionModel().selectFirst();
}
}
FXML file:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.ComboBox?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<top>
<ComboBox fx:id="combo" />
</top>
</BorderPane>
Test:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("sample.fxml")), 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
来源:https://stackoverflow.com/questions/37530239/combobox-in-javafx-application-doesnt-show-the-data