I don't succeed in filling a tableView with data, although I managed it before in exactly (as it appears to me ...) the same way.
(By the way: is there a way to display in one column not an object, that is referenced in the class I'm presenting in the tableView (such as FAVORITEBOOK), but an attribute-object of this object (such as the TITLE of the FAVORITEBOOK? Thanks!)
My Main class:
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.ArrayList;
public class Main extends Application {
Student student1 = new Student(0, "Jennifer", new Book("JavaFX for Dummies"));
Student student2 = new Student(1, "John", new Book("Cooking with Jamie Oliver"));
Student student3 = new Student(2, "Barbara", new Book("Jokes from Germany"));
ObservableList<Student> studentsObservable = FXCollections.observableArrayList(student1, student2, student3);
public static void main (String[] args) {
launch (args);
}
public void start (Stage primaryStage) throws Exception {
TableColumn<Student, Integer> idCol = new TableColumn<>("id");
TableColumn<Student, String> nameCol = new TableColumn<>("name");;
TableColumn<Student, Book> favoriteBookCol = new TableColumn<>("favoriteBook");;
TableView tableView = new TableView();
tableView.getColumns().setAll(idCol, nameCol, favoriteBookCol);
idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
favoriteBookCol.setCellValueFactory(new PropertyValueFactory<>("favoriteBook"));
tableView.setItems(studentsObservable);
HBox root = new HBox();
root.getChildren().add(tableView);
Scene scene = new Scene (root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
the classes Student and Book:
public class Student {
Integer id;
String name;
Book favoriteBook;
public Student (Integer id, String name, Book favoriteBook) {
this.id = id;
this.name = name;
this.favoriteBook = favoriteBook;
}
}
public class Book {
String title;
public Book (String title) {
this.title = title;
}
}
Thank you very much indeed for your effort and time!