如何解决JavaFX:tableView 仍然为空“IllegalStateException:无法读取不可读的属性”
我没有成功地用数据填充 tableView,尽管我之前完全以同样的方式管理它(在我看来......)。
(顺便说一句:有没有一种方法可以在一列中显示而不是在我在 tableView 中呈现的类(例如 FAVORITEBOOK)中引用的对象,而是该对象的属性对象(例如作为 FAVORITEBOOK 的标题?谢谢!)
我的主课:
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();
}
}
Student 和 Book 类:
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;
}
}
非常感谢您的努力和时间!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。