At a minimum, you need three classes: one for representing your data, one for your user interface and one for managing your database connection. Of course, in a real application you will need more than that. This example follows the same basic example as the TableView tutorial .
Suppose your database has a person table with three columns, first_name , last_name , email_address .
Then you should write the person class:
import javafx.beans.property.StringProperty ; import javafx.beans.property.SimpleStringProperty ; public class Person { private final StringProperty firstName = new SimpleStringProperty(this, "firstName"); public StringProperty firstNameProperty() { return firstName ; } public final String getFirstName() { return firstNameProperty().get(); } public final void setFirstName(String firstName) { firstNameProperty().set(firstName); } private final StringProperty lastName = new SimpleStringProperty(this, "lastName"); public StringProperty lastNameProperty() { return lastName ; } public final String getLastName() { return lastNameProperty().get(); } public final void setLastName(String lastName) { lastNameProperty().set(lastName); } private final StringProperty email = new SimpleStringProperty(this, "email"); public StringProperty emailProperty() { return email ; } public final String getEmail() { return emailProperty().get(); } public final void setEmail(String email) { emailProperty().set(email); } public Person() {} public Person(String firstName, String lastName, String email) { setFirstName(firstName); setLastName(lastName); setEmail(email); } }
Class for accessing data from a database:
import java.sql.Connection ; import java.sql.DriverManager ; import java.sql.SQLException ; import java.sql.Statement ; import java.sql.ResultSet ; import java.util.List ; import java.util.ArrayList ; public class PersonDataAccessor {
And then the user interface class:
import javafx.application.Application ; import javafx.scene.control.TableView ; import javafx.scene.control.TableColumn ; import javafx.scene.control.cell.PropertyValueFactory ; import javafx.scene.layout.BorderPane ; import javafx.scene.Scene ; import javafx.stage.Stage ; public class PersonTableApp extends Application { private PersonDataAccessor dataAccessor ; @Override public void start(Stage primaryStage) throws Exception { dataAccessor = new PersonDataAccessor(...);
(I just typed this without testing, so there may be typos, missing imports, etc., but that should be enough to give you this idea.)
James_d
source share