So the thing that i want to happen, is making the tableview update the data in the database after editing it. I wanted to use the SetOnEditCommit method here. The cell editing does work, but it never gets updated, with no error either. In the first place im a bit clueless if this method is actually efficient (probably not), since its hard to find some sources for this specific thing. And the sources that i found weren't really helpful. So it would be nice if someone had an idea as to why it doesn't update, or maybe provide an alternate option here.
The mentioned part:
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
full controller class:
package simple;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
*
* #author admin
*/
public class FXMLUserController extends SimpleController implements Initializable {
#FXML
public TableView<UserDetails> tableview;
#FXML
public TableColumn<UserDetails, String> columnId;
#FXML
public TableColumn<UserDetails, String> columnType;
#FXML
public TableColumn<UserDetails, String> columnKleur;
#FXML
public TableColumn<UserDetails, String> columnLuchthaven;
#FXML
public TableColumn<UserDetails, String> columnKenmerken;
#FXML
public TableColumn<UserDetails, String> columnStatus;
#FXML
public TableColumn<UserDetails, String> columnDatum;
#FXML
private Button btnLoad;
//declare observable list for database data
private ObservableList<UserDetails> data;
private DbConnection dc;
String c1;
#FXML
//strings for getRow method
#Override
public void initialize(URL url, ResourceBundle rb) {
dc = new DbConnection();
loadDataFromDatabase();
}
#FXML
public void loadDataFromDatabase() {
try {
Connection conn = dc.Connect();
data = FXCollections.observableArrayList();
// Execute query and store result in a resultset
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM gevonden_bagage");
while (rs.next()) {
//get strings
data.add(new UserDetails(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6), rs.getString(7)));
}
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
//Set cell values to tableview.
tableview.setEditable(true);
tableview.getSelectionModel().setCellSelectionEnabled(true);
columnType.setCellFactory(TextFieldTableCell.forTableColumn());
columnKleur.setCellFactory(TextFieldTableCell.forTableColumn());
columnLuchthaven.setCellFactory(TextFieldTableCell.forTableColumn());
columnKenmerken.setCellFactory(TextFieldTableCell.forTableColumn());
columnStatus.setCellFactory(TextFieldTableCell.forTableColumn());
columnDatum.setCellFactory(TextFieldTableCell.forTableColumn());
//makes columns editable
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnType.setCellValueFactory(new PropertyValueFactory<>("type"));
columnKleur.setCellValueFactory(new PropertyValueFactory<>("kleur"));
columnLuchthaven.setCellValueFactory(new PropertyValueFactory<>("luchthaven"));
columnKenmerken.setCellValueFactory(new PropertyValueFactory<>("kenmerken"));
columnStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
columnDatum.setCellValueFactory(new PropertyValueFactory<>("datum"));
columnType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<UserDetails, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<UserDetails, String> event) {
updataData();
}
});
tableview.setItems(null);
tableview.setItems(data);
}
public void updataData() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
Statement con = connection.createStatement();
//connection
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
String data1 = (String) col.getCellObservableValue(row).getValue();
//cell
UserDetails row1 = tableview.getSelectionModel().getSelectedItem();
c1 = row1.getId();
//row
//tableview variables
con.execute("UPDATE gevonden_bagage SET type = 'data1' WHERE koffer_id = 'c1' ");
//Query
} catch (SQLException ex) {
System.err.println("Error" + ex);
}
}
//get connection, get celldata, get id data from first row, update cell with selected id
#FXML
public void getRow() {
TablePosition pos = tableview.getSelectionModel().getSelectedCells().get(0);
int row = pos.getRow();
TableColumn col = pos.getTableColumn();
// this gives the value in the selected cell:
String data1 = (String) col.getCellObservableValue(row).getValue();
System.out.println(data1);
//CURRENTLY UNUSED METHOD
}
}
Model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* #author admin
*/
public class UserDetails {
private final StringProperty id;
private final StringProperty type;
private final StringProperty kleur;
private final StringProperty luchthaven;
private final StringProperty kenmerken;
private final StringProperty status;
private final StringProperty datum;
//Default constructor
public UserDetails(String id, String type, String kleur, String luchthaven, String kenmerken, String status, String datum) {
this.id = new SimpleStringProperty(id);
this.type = new SimpleStringProperty(type);
this.kleur = new SimpleStringProperty(kleur);
this.luchthaven = new SimpleStringProperty(luchthaven);
this.kenmerken = new SimpleStringProperty(kenmerken);
this.status = new SimpleStringProperty(status);
this.datum = new SimpleStringProperty(datum);
}
//getters
public String getId() {
return id.get();
}
public String getType() {
return type.get();
}
public String getKleur() {
return kleur.get();
}
public String getLuchthaven() {
return luchthaven.get();
}
public String getKenmerken() {
return kenmerken.get();
}
public String getStatus() {
return status.get();
}
public String getDatum() {
return datum.get();
}
//setters
public void setId(String value) {
id.set(value);
}
public void setType(String value) {
type.set(value);
}
public void setKleur(String value) {
kleur.set(value);
}
public void setLuchthaven(String value) {
luchthaven.set(value);
}
public void setKenmerken(String value) {
kenmerken.set(value);
}
public void setStatus(String value) {
status.set(value);
}
public void setDatum(String value) {
datum.set(value);
}
//property values
public StringProperty idProperty() {
return id;
}
public StringProperty typeProperty() {
return type;
}
public StringProperty kleurProperty() {
return kleur;
}
public StringProperty luchthavenProperty() {
return luchthaven;
}
public StringProperty kenmerkenProperty() {
return kenmerken;
}
public StringProperty statusProperty() {
return status;
}
public StringProperty datumProperty() {
return datum;
}
}
From the TableView documentation:
By default the TableColumn edit commit handler is non-null, with a
default handler that attempts to overwrite the property value for the
item in the currently-being-edited row. It is able to do this as the
Cell.commitEdit(Object) method is passed in the new value, and this is
passed along to the edit commit handler via the CellEditEvent that is
fired. It is simply a matter of calling
TableColumn.CellEditEvent.getNewValue() to retrieve this value.
It is very important to note that if you call
TableColumn.setOnEditCommit(javafx.event.EventHandler) with your own
EventHandler, then you will be removing the default handler. Unless
you then handle the writeback to the property (or the relevant data
source), nothing will happen.
So the problem is that by setting the onEditCommit on columnType, you remove the default handler that actually updates typeProperty in the UserDetails instance. Consequently
String data1 = (String) col.getCellObservableValue(row).getValue();
gives the old value, and your update to the database won't change anything.
Additionally, you have errors in the way you create the SQL statement. You are making the id in the WHERE clause the literal value 'c1' (instead of the value contained in the variable c1, and similarly setting the value of type to the literal value 'data1', instead of the value in the variable data1.
Here is a fix, along with some simplification of the code and some better practices for avoiding SQL injection attacks:
columnType.setOnEditCommit(event -> {
UserDetails user = event.getRowValue();
user.setType(event.getNewValue());
updateData("type", event.getNewValue(), user.getId());
});
and then
private void updateData(String column, String newValue, String id) {
// btw it is way better to keep the connection open while the app is running,
// and just close it when the app shuts down....
// the following "try with resources" at least makes sure things are closed:
try (
Connection connection = DriverManager.getConnection("jdbc:mysql://37.128.148.113:3306/FYS", "FYS", "Kcj8g87~");
PreparedStatement stmt = connection.prepareStatement("UPDATE gevonden_bagage SET "+column+" = ? WHERE koffer_id = ? ");
) {
stmt.setString(1, newValue);
stmt.setString(2, id);
stmt.execute();
} catch (SQLException ex) {
System.err.println("Error");
// if anything goes wrong, you will need the stack trace:
ex.printStackTrace(System.err);
}
}
Related
I was trying to add data to my tableView in my JavaFX app. I am using hibernate to do operations on my Database. I used a query to get all the orders and store each order in an object and added the object to the observable list of the tableView. I created the orders class and mapped it to my database. This is the class of the orders:
#Entity
#Table(name = "orders")
public class orders implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "order_id")
private int order_id;
#JoinColumn(name = "item_id")
#ManyToOne
#NotNull
private items item_id;
#Column(name = "quantity")
#NotNull
private int quantity;
#Column(name = "price_per_unit")
#NotNull
private double price_per_unit;
#Column(name = "total_price")
#NotNull
private double total_price;
#Column(name = "order_date")
#NotNull
private Date order_date;
#JoinColumn(name = "user_id")
#ManyToOne
#NotNull
private users user_id;
public orders() {
}
public orders(int order_id, items item_id, int quantity, double price_per_unit, double total_price, Date order_date, users user_id) {
this.order_id = order_id;
this.item_id = item_id;
this.quantity = quantity;
this.price_per_unit = price_per_unit;
this.total_price = total_price;
this.order_date = order_date;
this.user_id = user_id;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public items getItem_id() {
return item_id;
}
public void setItem_id(items item_id) {
this.item_id = item_id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice_per_unit() {
return price_per_unit;
}
public void setPrice_per_unit(double price_per_unit) {
this.price_per_unit = price_per_unit;
}
public double getTotal_price() {
return total_price;
}
public void setTotal_price(double total_price) {
this.total_price = total_price;
}
public Date getOrder_date() {
return order_date;
}
public void setOrder_date(Date order_date) {
this.order_date = order_date;
}
public users getUser_id() {
return user_id;
}
public void setUser_id(users user_id) {
this.user_id = user_id;
}
}
And the below code is the code of the view in which I have the tableView that loads the orders and displays the orders from the database:
public class OrdersPageController implements Initializable {
private Main app;
private Session session;
private Transaction transaction = null;
#FXML
private TableView<orders> table;
public void setApp(Main app) {
this.app = app;
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
public void goBack(ActionEvent event){
session.close();
transaction = null;
app.goToHomePage();
}
public void processLogout(ActionEvent event){
session.close();
transaction = null;
app.userLogout();
}
public void addOrder(ActionEvent event){
session.close();
transaction = null;
app.addOrdersPage();
}
public void deleteOrder(ActionEvent event){
session.close();
transaction = null;
app.closeOrdersPage();
}
public void getOrders(){
try{
String hql = "FROM orders";
Query query = session.createQuery(hql);
List<orders> list = query.getResultList();
for (orders o : list) {
//Create an order object
orders order = new orders();
order.setOrder_id(o.getOrder_id());
order.setItem_id(o.getItem_id());
order.setPrice_per_unit(o.getPrice_per_unit());
order.setQuantity(o.getQuantity());
order.setOrder_date(o.getOrder_date());
order.setTotal_price(o.getTotal_price());
order.setUser_id(o.getUser_id());
//Create an observable list for the table
ObservableList<orders> tableList = table.getItems();
//Add the order object to the list
tableList.add(order);
//Set the created list to the table to show data
table.setItems(tableList);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.close();
}
}
}
Note that the getOrders method is the method that gets the orders from the database and sets the observable list of the tableView.
I am having problem displaying the item_id and the user_id of the order. I think the problem is that they both are objects of type items and users respectively and the table displays the address of the objects. Instead I want to display the numbers of the ids of the item ordered and the user that made the order. If you know what I can do to fix my problem please share it with me.
Add cellFactorys to the relevant columns. You haven't shown the FXML in the question, so I don't know the names you assigned to the appropriate TableColumn instances, but you can do something like this:
public class OrdersPageController implements Initializable {
// ...
#FXML
private TableView<orders> table;
#FXML
private TableColumn<orders, users> userColumn ;
#Override
public void initialize(URL url, ResourceBundle rb) {
userColumn.setCellFactory(tc -> new TableCell<>() {
#Override
protected void updateItem(users user, boolean empty) {
super.updateItem(user, empty);
if (empty || user == null) {
setText("");
} else {
String text = /* anything you need based on user */
setText(text);
}
}
});
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
//Fill the table view
getOrders();
}
}
Just override toString method in users and items Classes:
Example: in your users Class ->
#Override
public String toString() {
return user_id.toString();
}
As James_D stated, have a look on java conventions. Java Classes should be always be with Capital Letter.
I want to create a simple table with multiple selection using checkboxes on the first column.
I've created a custom "TableColumn" to handle this feature in every table I need. I've implemented all the features except one: when I select or deselect a single row the corresponding checkbox on the first colum must be selected or unselected. I need help to develop this last function.
public class ColumnSelectRow extends TableColumn{
private CheckBox headerCheckBox = new CheckBox();
public ColumnSelectRow(String title) {
super(title);
setSortable(false);
setPrefWidth(100);
setMaxWidth(100);
setMinWidth(100);
setResizable(false);
setGraphic(headerCheckBox);
setCellValueFactory( new Callback<TableColumn.CellDataFeatures<Object, Boolean>, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Object, Boolean> p) {
return new SimpleBooleanProperty(p.getValue() != null);
}
});
setCellFactory(new Callback<javafx.scene.control.TableColumn<Object, Boolean>, TableCell<Object, Boolean>>() {
#Override
public TableCell<Object, Boolean> call(javafx.scene.control.TableColumn<Object, Boolean> p) {
return new SelectButtonCell();
}
});
headerCheckBox.setOnAction(t->{
if(disableEvents) return;
TableView table = ColumnSelectRow.this.getTableView();
if (table == null) return;
if(headerCheckBox.isSelected()) table.getSelectionModel().selectAll();
else table.getSelectionModel().clearSelection();
});
}
public CheckBox getHeaderCheckBox() {
return headerCheckBox;
}
private boolean disableEvents = false;
private class SelectButtonCell extends TableCell {
private final CheckBox checkBox = new CheckBox();
public SelectButtonCell(){
setAlignment(Pos.CENTER);
checkBox.setOnAction(t -> {
int row = getTableRow().getIndex();
TableView table = SelectButtonCell.this.getTableView();
if (table == null) return;
if(checkBox.isSelected()) table.getSelectionModel().select(row);
else table.getSelectionModel().clearSelection(row);
table.getFocusModel().focus(row);
boolean empty = table.getSelectionModel().isEmpty();
boolean full = table.getSelectionModel().getSelectedCells().size()==table.getItems().size();
disableEvents = true;
headerCheckBox.setIndeterminate(false);
if(empty) headerCheckBox.setSelected(false);
else if(full) headerCheckBox.setSelected(true);
else headerCheckBox.setIndeterminate(true);
disableEvents = false;
});
}
public CheckBox getCheckBox() {
return checkBox;
}
#Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if(!empty){
setGraphic(checkBox);
}
int row = getTableRow().getIndex();
TableView table = SelectButtonCell.this.getTableView();
checkBox.setSelected(table.getSelectionModel().isSelected(row));
}
public boolean isCheckBoxSelected(){
return checkBox.isSelected();
}
}
thanks!!
Edit: a custom table with the first column selectable
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class MyTable extends Application {
private ColumnSelectRow columSelect;
#Override
public void start(Stage primaryStage) throws Exception {
columSelect = new ColumnSelectRow();
TableView T = new TableView<>();
T.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
ObservableList<myObject> al = FXCollections.observableArrayList();
al.add(new myObject(1));
al.add(new myObject(2));
al.add(new myObject(3));
T.setItems(al);
T.getColumns().add(columSelect);
TableColumn<myObject, Number> number = new TableColumn("Number");
number.setCellValueFactory(cellData->cellData.getValue().propetry);
T.getColumns().add(number);
Scene scene = new Scene(T);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private class myObject{
public SimpleIntegerProperty propetry = new SimpleIntegerProperty();
public myObject(int i) {
propetry.set(i);
}
}
}
i followed the instructions from this question to set a ComboBoxCell in the TableView of my application. (How to put ComboBoxTableCell in a TableView?)
The declaration of the Cell works fine, but the comboBox doesn't appear in the table. I think it's like this, because only col1 and col2 are in my model. col3 is not written in my table-entry after the database connection.
I don't know how to takte the ComboBox in the TableView and need your help.
Here is my code:
controller:
package controller;
imports
public class main_controller implements Initializable {
private ObservableList<model> tableData = FXCollections.observableArrayList();
private ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
#FXML
private TableView<model> ComboTable;
#FXML
private TableColumn<model, String> col1;
#FXML
private TableColumn<model, String> col2;
#FXML
private TableColumn<model, String> col3;
public main_controller() {
}
#Override
public void initialize(URL location, ResourceBundle resources) {
tableData.clear();
col1.setCellValueFactory(new PropertyValueFactory<model, String>("rCol1"));
col2.setCellValueFactory(new PropertyValueFactory<model, String>("rCol2"));
col3.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.56:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT NUMMER, DATEN1, DATEN2 FROM LUKAS order by NUMMER");
String Daten1 = "empty";
String Daten2 = "empty";
// Zum einfügen kann man später auf diese Variable zurückgreifen.
int columnIndex;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
columnIndex = resultset.getInt("NUMMER");
System.out.println("Tabellenindex der Zeile:\t" + columnIndex);
Daten1 = resultset.getString("DATEN1");
Daten2 = resultset.getString("DATEN2");
System.out.println("Daten1:\t " + Daten1 + "\t\t\tDaten2: " + Daten2);
**model entry = new model(Daten1, Daten2);
tableData.add(entry);**
}
System.out.println("*** Database data saved to Observable List named 'data' ***");
ComboTable.setItems(tableData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
model:
package model;
import javafx.beans.property.SimpleStringProperty;
public class model {
private final SimpleStringProperty rCol1;
private final SimpleStringProperty rCol2;
public model(String sCol1, String sCol2) {
this.rCol1 = new SimpleStringProperty(sCol1);
this.rCol2 = new SimpleStringProperty(sCol2);
}
public String getRCol1() {
return rCol1.get();
}
public void setRCol1(String set) {
rCol1.set(set);
}
public String getRCol2() {
return rCol2.get();
}
public void setRCol2(String set) {
rCol2.set(set);
}
}
The application looks like this right now:
Picture
Hope you can help me!
The declaration of the Cell works fine, but the comboBox doesn't
appear in the table.
The combobox of ComboBoxTableCell will be appeared when this cell is in edit mode. To do that you need to set the tableview to editable and then double click the over mentioned cell.
The quote from the ComboBoxTableCell javadoc:
By default, the ComboBoxTableCell is rendered as a Label when not
being edited, and as a ComboBox when in editing mode. The ComboBox
will, by default, stretch to fill the entire table cell.
Can anyone give me one example of a class that connects JavaFX with MySQL, dont want Main class, have one, just want a example of a class that connects any application to a MySQL database and gets a row from that database into a table, searched the whole internet and i didn't find anything straight to the point i do not want anything fancy just something to get the job done please.
Something clean and simple.
At a minimum, you need three classes: one to represent your data, one for your UI, and one to manage the database connection. In a real app you'd need more than this, of course. 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 would write a 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);
}
}
A class to access the data from the 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 {
// in real life, use a connection pool....
private Connection connection ;
public PersonDataAccessor(String driverClassName, String dbURL, String user, String password) throws SQLException, ClassNotFoundException {
Class.forName(driverClassName);
connection = DriverManager.getConnection(dbURL, user, password);
}
public void shutdown() throws SQLException {
if (connection != null) {
connection.close();
}
}
public List<Person> getPersonList() throws SQLException {
try (
Statement stmnt = connection.createStatement();
ResultSet rs = stmnt.executeQuery("select * from person");
){
List<Person> personList = new ArrayList<>();
while (rs.next()) {
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String email = rs.getString("email_address");
Person person = new Person(firstName, lastName, email);
personList.add(person);
}
return personList ;
}
}
// other methods, eg. addPerson(...) etc
}
And then a UI 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(...); // provide driverName, dbURL, user, password...
TableView<Person> personTable = new TableView<>();
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<Person, String> emailCol = new TableColumn<>("Email");
emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
personTable.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
personTable.getItems().addAll(dataAccessor.getPersonList());
BorderPane root = new BorderPane();
root.setCenter(personTable);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop() throws Exception {
if (dataAccessor != null) {
dataAccessor.shutdown();
}
}
public static void main(String[] args) {
launch(args);
}
}
(I just typed that in without testing, so there may be typos, missing imports, etc, but it should be enough to give you the idea.)
In addition to the answer of James_D:
I wanted to connect to a remote (MySQL) database, so I changed the constructor and connected by url-only:
public UserAccessor(String dbURL, String user, String password) throws SQLException, ClassNotFoundException {
connection = DriverManager.getConnection(dbURL, user, password);
}
Init via:
UserAccessor userAccessor = new UserAccessor(
"jdbc:mysql://xxx.xxx.xxx.xxx:YOUR_PORT", "YOUR_DB_USER", "YOUR_PASSWORD")
Please note:
You will also need to include the connector lib. I choosed mysql-connector-java-5.1.40-bin.jar which came with IntelliJ and was located under /Users/martin/Library/Preferences/IntelliJIdea2017.1/jdbc-drivers/MySQL Connector/J/5.1.40/mysql-connector-java-5.1.40-bin.jar
Kudos belong to James_D.
I'm still new to JavaFX and need to create a combobox with objects (SimlpePerson) and not strings. I want to edit the shown value in the box itself. Works good for strings but I have problems with SimpleObjects. I made a StringConverter and it also works, I can edit the object shown in the comboBox. But the list itself is not rerendered after that. If I click on the ComboBox I see the original values. How can I change that?
Any suggestion is very welcome!=)
BR and Thank you!
Stefan
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboBoxDemo extends Application{
public class SimplePerson {
private StringProperty name;
private String somethingElse;
public SimplePerson(String name) {
setName(name);
}
public final void setName(String value) { nameProperty().set(value); }
public String getName() { return nameProperty().get(); }
public StringProperty nameProperty() {
if (name == null) name = new SimpleStringProperty(this, "name");
return name;
}
}
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob"),
new SimplePerson("Isabella"),
new SimplePerson("Ethan"),
new SimplePerson("Emma"),
new SimplePerson("Michael")
);
#Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
final ComboBox cb = new ComboBox();
cb.setItems(persons);
cb.setEditable(true);
cb.setConverter(new StringConverter<SimplePerson>() {
#Override
public String toString(SimplePerson p)
{
if(p != null)
return p.getName();
return "";
}
#Override
public SimplePerson fromString(String name)
{
if(cb.getValue() != null)
{
((SimplePerson)cb.getValue()).setName(name);
cb.show();
return (SimplePerson)cb.getValue();
}
return null;
}
});
stage.setScene(new Scene(cb));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
Check out this solution. There is a handler which is triggered when you've finished editing. There you may implement all the code which changes the model's state.
To update the combobox list the following approach work may:
cb.getEditor().setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
SimplePerson person = cb.getValue();
if (null != person) {
int idx = persons.indexOf(person);
person.setName(cb.getEditor().getText());
persons.set(idx, person);
cb.setValue(person);
}
}
});