Records is a new feature with Java 16. Defined in JEP 395: Records.
Suppose you have a record such as this one.
public record Person(String last, String first, int age)
{
public Person()
{
this("", "", 0);
}
}
This is a final class. It automatically generates the getter methods first(), last(), and age().
Now here is a TableView in JavaFX.
/**************************************************
* Author: Morrison
* Date: 10 Nov 202021
**************************************************/
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
public class TV extends Application
{
public TV()
{
}
@Override
public void init()
{
}
@Override
public void start(Stage primary)
{
BorderPane root = new BorderPane();
TableView<Person> table = new TableView<>();
root.setCenter(table);
TableColumn<Person, String> lastColumn = new TableColumn<>("Last");
lastColumn.setCellValueFactory(new PropertyValueFactory<Person,
String>("last"));
TableColumn<Person, String> firstColumn = new TableColumn<>("First");
firstColumn.setCellValueFactory(new PropertyValueFactory<Person,
String>("first"));
TableColumn<Person, Integer> ageColumn = new TableColumn<>("Age");
ageColumn.setCellValueFactory(new PropertyValueFactory<Person,
Integer>("age"));
table.getColumns().add(lastColumn);
table.getColumns().add(firstColumn);
table.getColumns().add(ageColumn);
table.getItems().add(new Person("Smith", "Justin", 41));
table.getItems().add(new Person("Smith", "Sheila", 42));
table.getItems().add(new Person("Morrison", "Paul", 58));
table.getItems().add(new Person("Tyx", "Kylee", 40));
table.getItems().add(new Person("Lincoln", "Abraham", 200));
Scene s = new Scene(root, 500, 500);
primary.setTitle("TableView Demo");
primary.setScene(s);
primary.show();
}
@Override
public void stop()
{
}
}
The problem lies here.
TableColumn<Person, String> lastColumn = new TableColumn<>("Last");
lastColumn.setCellValueFactory(new PropertyValueFactory<Person,
String>("last"));
The TableView is expecting methods of name getFirst
, getLast
, and getAge
to do its work. Is there a workaround other than doing this horrible thing?
public record Person(String last, String first, int age)
{
public Person()
{
this("", "", 0);
}
public String getLast()
{
return last;
}
public String getFirst()
{
return first;
}
public int getAge()
{
return age;
}
}
TableView
written using Java 8 or later. Just implement thecellValueFactory
for each column. – Historical