Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a simple row to JavaFx tableView

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

like image 821
Danial Kosarifa Avatar asked Sep 07 '16 10:09

Danial Kosarifa


People also ask

How do you populate a table in JavaFX?

The most important classes for creating tables in JavaFX applications are TableView , TableColumn , and TableCell . You can populate a table by implementing the data model and by applying a cell factory. The table classes provide built-in capabilities to sort data in columns and to resize columns when necessary.

How to select a row in TableView JavaFX?

To select a row with a specific index you can use the select(int) method. Here is an example of selecting a single row with a given index in a JavaFX TableView: selectionModel. select(1);


1 Answers

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);
like image 88
Dth Avatar answered Oct 25 '22 06:10

Dth