为了账号安全,请及时绑定邮箱和手机立即绑定

JavaFx自定义ListCell为空

JavaFx自定义ListCell为空

胡说叔叔 2023-07-28 09:41:16
ListCell我正在尝试为 JavaFX创建一个非常简单的自定义Listview。运行应用程序时,有一些项目没有ListView任何内容。它们是可点击的,但是是空的。如下图所示:我正在使用 JDK 12 和基于 Maven JFX Archetype(archetype-artifactid:javafx-archetype-fxml, groupid:org.openjfx) 的设置。我遵循了名为“Turais Custom ListCell”的指南。App.javapublic class App extends Application {private static Scene scene;@Overridepublic void start(Stage stage) throws IOException {    scene = new Scene(loadFXML("primary"));    stage.setScene(scene);    stage.show();}static void setRoot(String fxml) throws IOException {    scene.setRoot(loadFXML(fxml));}private static Parent loadFXML(String fxml) throws IOException {    FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));    return fxmlLoader.load();}public static void main(String[] args) {    launch();}}PrimaryController.javapublic class PrimaryController implements Initializable {ObservableList<Student> students;@FXMLprivate ListView<Student> listView1;@FXMLprivate void switchToSecondary() throws IOException {    App.setRoot("secondary");}public PrimaryController(){    super();    students = FXCollections.observableArrayList();   students.add(new Student());}@Overridepublic void initialize(URL url, ResourceBundle resourceBundle) {    listView1.setItems(students);    listView1.setCellFactory(new Callback<ListView<Student>, ListCell<Student>>() {        @Override        public ListCell<Student> call(ListView<Student> listView) {            return new StudentListViewCell();        }    });}}我希望有一个ListCell中间有一个标签,上面写着“rightText”的单曲。但似乎我的自定义列表单元格甚至没有呈现。有什么建议么?
查看完整描述

1 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

除了您的实现看起来比需要的复杂得多之外,您的实际问题非常简单。


您的ListCell.fxml文件未将 分配fx:id给您的AnchorPane. 因此,当您在StudentListViewCell.java类中定义它时,您实际上是在创建一个新的AnchorPane且不包含您的Label.


只需更改ListCell.fxml文件并分配 id 即可解决该问题:


<AnchorPane fx:id="anchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea"

            xmlns:fx="http://javafx.com/fxml/1">

    <children>

        <Label fx:id="label1" layoutX="293.0" layoutY="190.0" text="Label"/>

    </children>

</AnchorPane>


查看完整回答
反对 回复 2023-07-28
  • 1 回答
  • 0 关注
  • 79 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信