最近在做一个业余PC端项目,为了尽可能跨平台,选择了JavaFX构建项目的UI逻辑。其中有一个模块需要用TableView展示数据。我按照教程:
实现了我的窗体后运行,出现了如下报错:
Caused by: java.lang.IllegalAccessException: module javafx.base cannot access class com.bluepoint.bean.FileItem (in module com.bluepoint.bluepointdisk) because module com.bluepoint.bluepointdisk does not open com.bluepoint.bean to javafx.base
并且UI上没有如愿地显示出我的bean对象对应的数据。
回到教程的例子上,有一个地方引起了我的注意:
首先,列数据项中需要设置一个属性名:
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<>("firstName"));
而JavaBean中也有对应的属性方法:
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private Person(String fName, String lName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
}
这似乎说明了tableView很可能是通过反射的方法,从bean对象中取出对应关键字的数据,那么根据错误信息,很可能是反射过程中无法找到类文件,可能是需要配置些什么东西。仔细观察InteliJ创建的工程,发现了这个文件: java/module-info.java
内容如下:
module com.bluepoint.bluepointdisk {
requires javafx.controls;
requires javafx.fxml;
requires javafx.web;
requires org.controlsfx.controls;
requires com.dlsc.formsfx;
requires validatorfx;
requires org.kordamp.ikonli.javafx;
requires org.kordamp.bootstrapfx.core;
requires eu.hansolo.tilesfx;
opens com.bluepoint.bluepointdisk to javafx.fxml;
exports com.bluepoint.bluepointdisk;
}
按照文件的结构猜测,javafx.fxml之所以可以访问我的工程的文件,应该就是opens中进行了配置。然后我照着格式添加了一行配置:
opens com.bluepoint.bean to javafx.base;
重新编译,执行。数据例子终于跑通了,也没有报错了。