为了处理数据库中的数据,我实现了表数据网关。所以,我有两个表:
CREATE TABLE student (
id INT,
id groupId,
name VARCHAR(100),
surname VARCHAR(100)
);
CREATE TABLE group (
id INT,
name VARCHAR(100)
);
我有两个 DTO。严格地说,一张表一个 DTO
class Student{
private int id;
private int groupId;
private String name;
private String surname;
//+getters and setters
}
class Group{
private int id;
private String name;
//+getters and setters
}
我有两个 TableDataGateway 类,用于加载 DTO 并将其保存到数据库。
class StudentTableDataGateway extends AbstractTableDataGateway{
....
}
class GroupTableDataGateway extends AbstractTableDataGateway{
....
}
现在我想通过 javafx 创建包含以下列的学生表:
|Student ID|Student Name|Student Surname|Group Name|
我就到此为止了。我不明白如何为 TableView 构建数据以及下一步应该做什么。请帮助我。
编辑1
最困难的部分(最让我困惑的部分)是如何链接从学生对象中的组对象获取数据?因为,在学生类(class)领域中制作“私有(private)小组”是非常不可取的。原因是,如果我们为每个 TableView 都修改域类,它们将非常糟糕。例如,如果我们需要创建另一个包含列的 TableView :
|student name|student surname|teacher name
那么我们要不要在Student类中再添加一个字段呢?
最佳答案
如果您有 setter/getter ,您唯一需要做的就是为您的表创 build 置表属性。示例:
TableView<Student> table = new TableView<>();
TableColumn<Student,Integer> userId = new TableColumn<>("User Id");
userId.setCellValueFactory(new PropertyValueFactory<>("id"));
这将在您的 Student 对象类中查找 getId()
并从中添加数据。
唯一棘手的部分是组名称,因为它位于不同的类中。我可能只会在学生类中包含辅助方法。你不需要在那里拥有任何属性(property)。只需要类似 getter 的方法
public String getGroupName() {
return ""//Code to find group name here;
}
这是本例中您需要的所有代码:
ObservableList<Student> students = FXCollections.observableArrayList();
students.addAll(one);
TableView<Student> table = new TableView<>();
TableColumn<Student,Integer> userId = new TableColumn<>("User Id");
userId.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<Student,String> groupName = new TableColumn<>("Group Name");
groupName.setCellValueFactory(new PropertyValueFactory<>("groupName"));
TableColumn<Student,String> name = new TableColumn<>("User Name");
name.setCellValueFactory(new PropertyValueFactory<>("name"));
TableColumn<Student,String> surname = new TableColumn<>("User Surname");
surname.setCellValueFactory(new PropertyValueFactory<>("surname"));
table.getColumns().addAll(userId,groupId,name,surname);
table.setItems(students);
但 groupName 总是有其他选项:
1) 创建自定义 CellValueFactory 和 setCellValueFactory()
groupName.setCellValueFactory(data->{
Student student = data.getValue();
String strGroupName = "";// calculate group name for...
return new ReadOnlyStringWrapper(strGroupName);
}
);
2) 使用您需要的所有 getter 创建缓冲区对象
关于JavaFx TableView 、表网关模式和联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670082/