为什么我的JavaFX TableView是空的
我在TableView中添加了默认的TEST1和TEST2作为Name Col,但是在运行它时没有显示。 这里有两个类和一个我用过的fxml,有人可以给我一些关于这个问题的建议吗?
只有一个包调用:controllerJBoxFXTest
第一类MainView.class包controllerJBoxFXTest;
import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; public class MainView extends Application { public static void main(String[] args){ Application.launch(MainView.class, (java.lang.String[]) null); } @Override public void start(Stage primaryStage) throws Exception { try { AnchorPane Page = (AnchorPane) FXMLLoader.load(MainView.class.getResource("MainController.fxml")); Scene scene = new Scene(Page); primaryStage.setScene(scene); primaryStage.setTitle("Test Main"); primaryStage.show(); } catch (Exception e){ Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, e); } } }
第二个MainController.java,你可以看到我添加了TEST1和TEST2包的controllerJBoxFXTest;
import java.net.URL; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.beans.property.SimpleStringProperty; public class MainController implements Initializable{ @FXML TableView tableID; @FXML TableColumn iName; public class Table { private final SimpleStringProperty rName; public Table(String sName) { this.rName = new SimpleStringProperty(sName); } public String getName(){ return rName.get(); } public void setName(String vName) { this.rName.set(vName); } } final ObservableList data = FXCollections.observableArrayList( new Table("TEST1"), new Table("TEST2") ); @Override public void initialize(URL location, ResourceBundle resources) { iName.setCellValueFactory(new PropertyValueFactory("rName")); tableID.setItems(data); } }
3rd这是由场景生成器生成的MainController.fxml
当我运行MainView.java时,有人能确定为什么我的TableView是空的吗? 谢谢,
传递给PropertyValueFactory
( rName
)的值与get和set方法名称在模型类Table
定义的属性不匹配。
由于您传递了“rName”,因此PropertyValueFactory
将首先查找名为rNameProperty()
的方法,返回ObservableValue
。 由于不存在,它将查找返回String
的方法getRName()
。 由于这两者都不存在,因此您无需在列中显示任何值。 (有关完整说明,请参阅Javadocs 。)
要么更改单元格值工厂:
iName.setCellValueFactory(new PropertyValueFactory("name"));
或者将Table
类中的方法名称更改为getRName()
和setRName(...)
。