Add a simple row to JavaFx tableView
Asked Answered
B

1

10

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 :)

Brody answered 7/9, 2016 at 10:1 Comment(2)
Table1.getItems() is where you can add rows.Kerrison
You cannot use TableView as a TableView column.Missy
U
27

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.

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;
    }
}

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);

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);
Unship answered 7/9, 2016 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.