首页 > 解决方案 > JavaFX:tableView 保持为空(“IllegalStateException:无法从不可读的属性中读取”)

问题描述

我没有成功地用数据填充 tableView,尽管我之前以完全相同的方式管理它(在我看来......)。

(顺便说一句:有没有办法在一个列中显示不是一个对象,即在我在 tableView 中呈现的类中引用(例如 FAVORITEBOOK),而是该对象的属性对象(例如 TITLE最喜欢的书?谢谢!)

我的主要课程:

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.util.ArrayList;

public class Main extends Application {

    Student student1 = new Student(0, "Jennifer", new Book("JavaFX for Dummies"));
    Student student2 = new Student(1, "John", new Book("Cooking with Jamie Oliver"));
    Student student3 = new Student(2, "Barbara", new Book("Jokes from Germany"));
    ObservableList<Student> studentsObservable = FXCollections.observableArrayList(student1, student2, student3);

    public static void main (String[] args) {

        launch (args);
    }

    public void start (Stage primaryStage) throws Exception {

        TableColumn<Student, Integer> idCol = new TableColumn<>("id");
        TableColumn<Student, String> nameCol = new TableColumn<>("name");;
        TableColumn<Student, Book> favoriteBookCol = new TableColumn<>("favoriteBook");;
        TableView tableView = new TableView();
        tableView.getColumns().setAll(idCol, nameCol, favoriteBookCol);

        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        favoriteBookCol.setCellValueFactory(new PropertyValueFactory<>("favoriteBook"));

        tableView.setItems(studentsObservable);

        HBox root = new HBox();
        root.getChildren().add(tableView);
        Scene scene = new Scene (root);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
}

学生和书籍类:

public class Student {
   Integer id;
   String name;
   Book favoriteBook;

   public Student (Integer id, String name, Book favoriteBook) {
       this.id = id;
       this.name = name;
       this.favoriteBook = favoriteBook;
   }
}

public class Book {
   String title;

   public Book (String title) {
       this.title = title;
   }
}

非常感谢您的努力和时间!

标签: javajavafxtableviewillegalstateexception

解决方案


推荐阅读