更新到Java 8后,我在显示列表视图的内容时出现问题
public class TestController extends AnchorPane implements Initializable {
@FXML
private ListView<String> listView;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setApp() {
setContent();
}
/**
* Set content in list
*/
private void setContent() {
ObservableList<String> items = FXCollections.observableArrayList();
items.add("1");
items.add("2");
listView.setItems(items);
}
}
使用Java 7,这给了我一个包含值的列表。更新到java 8后,它给了我一个空框架。
感谢James_D,这是您要求的代码
public void goToTest() {
try {
TestController test = (TestController) replaceSceneContent("/fxml/test.fxml");
test.setApp();
} catch (Exception ex) {
System.out.println("Error loading: " + ex + " - " + ex.getMessage());
}
}
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
InputStream in = MainApp.class.getResourceAsStream(fxml);
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(MainApp.class.getResource(fxml));
AnchorPane page;
try {
page = (AnchorPane) loader.load(in);
} finally {
in.close();
}
Scene scene = new Scene(page);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(resizable);
return (Initializable) loader.getController();
}
答案 0 :(得分:2)
listView = new ListView<>(items);
不起作用;它会创建一个新的ListView
并填充它,而你想要做的就是填充你在FXML中创建的ListView
。
listView.setItems(items);
是正确的代码。
(我假设你真的有public class TestController implements Initializable
,而不是public class test implements Initializable
。)
所以以下内容应该有效:
private void setContent() {
ObservableList<String> items = FXCollections.observableArrayList();
items.add("1");
items.add("2");
listView.setItems(items);
}
您的FXMLLoader
代码有点不寻常,因为您设置了位置(网址),但随后使用load(InputStream)
方法加载。如果能解决它,我会感到惊讶,但通常的方法是:
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
// not needed:
// InputStream in = MainApp.class.getResourceAsStream(fxml);
// Not really needed, this is the default:
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(MainApp.class.getResource(fxml));
AnchorPane page;
// instead of this:
// try {
// page = (AnchorPane) loader.load(in);
// } finally {
// in.close();
// }
// just this (since you have set the location):
page = loader.load();
Scene scene = new Scene(page);
stage.setScene(scene);
stage.sizeToScene();
stage.setResizable(resizable);
return (Initializable) loader.getController();
}
(随机猜测:你是不是意外地在控制器中使listView
静态了?)