向 JavaFx tableView 添加一个简单的行 [英] Add a simple row to JavaFx tableView

查看:157
本文介绍了向 JavaFx tableView 添加一个简单的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 TableView 和在 JavaFx 中自定义它很陌生.我经历了很多教程,我已经理解了一些,但仍然坚持在我的表格中添加行.例如,我有一个名为 Table1 的表.根据我的理解,我可以创建列 ArrayList 和:

I am quite new to TableView and customizing it in JavaFx. I've gone through many tutorial, I've understood some but stucked in adding rows into my table. For example, I have a table called Table1. According to my understanding I can create columns ArrayList and:

for (int i = 0; i <= columnlist.size() - 1; i++) {
    TableView col = new TableView(columnlist.get(i));
    Table1.getColumns().add(col);
}

现在我如何在其中添加一行?如果您能给我一个非常简单的例子,我将不胜感激,因为我已经看过其他例子,但它们太复杂了 :)

Now how can I add a row to this? I will appreciate if you can give me a very simple example as I have gone through other examples but they were too complex :)

推荐答案

您无法以这种方式创建列.TableView 构造函数采用 ObservableList 作为其参数,但它希望找到表值,即您的行.

You can't create your columns this way. TableView constructor takes an ObservableList as its parameter, but it expects to find there table values, in other words, your rows.

恐怕没有任何通用的方法可以将项目添加到您的表中,因为每个表或多或少都与其数据模型耦合.假设您有一个要显示的 Person 类.

I'm afraid that there isn't any generic way to add items to your table, because each table is more or less coupled to its data model. Let's say that you have a Person class which you want to display.

public class Person {
    private String name;
    private String surname;

    public Person(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }
}

为此,您必须创建表格及其两列.PropertyValueFactory 将从您的对象中获取必要的数据,但您必须确保您的字段具有遵循标准命名约定的访问器方法 (getName(), getSurname() 等).否则将无法工作.

In order to do that you'll have to create the table and its two columns. PropertyValueFactory will fetch the necessary data from your object, but you have to make sure that your fields have an accessor method that follows the standard naming convention (getName(), getSurname(), etc). Otherwise it will not work.

TableView tab = new TableView();

TableColumn nameColumn = new TableColumn("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

TableColumn surnameColumn = new TableColumn("Surname");
surnameColumn.setCellValueFactory(new PropertyValueFactory<>("surname"));

tab.getColumns().addAll(nameColumn, surnameColumn);

现在您要做的就是创建您的 Person 对象并将其添加到表项中.

Now all you have to do is to create your Person object and add it to the table items.

Person person = new Person("John", "Doe");
tab.getItems().add(person);

这篇关于向 JavaFx tableView 添加一个简单的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆