javaFX - tableview getting selected items - database

How can I get a selected item in a row from tableview in javaFX with Sqlite Database.
I am now using this to get the Index of the row:
(...)
#FXML
private ObservableList<UserData> data;
#FXML
private TableView table;
#FXML
private void pressTableAction() {
System.out.println("Selected index: " +table.getSelectionModel().getSelectedIndex());
}
(...)
public void initialize (URL url, ResourceBundle rb) {
try {
con = DataBaseConnection.getConnected();
stat = con.createStatement();
data = FXCollections.observableArrayList();
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM person");
while (rs.next()) {
data.add(new UserData(rs.getInt("p_id"), rs.getString("Name")));
}
column1.setCellValueFactory(new PropertyValueFactory("p_id"));
column2.setCellValueFactory(new PropertyValueFactory("Name"));
table.setItems(null);
table.setItems(data);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
Public static class UserData {
private IntegerProperty p_id;
private StringProperty Name;
private UserData(Integer p_id, String Name) {
this.p_id = new SimpleIntegerProperty (p_id);
this.Name = new SimpleStringProperty(Name);
}
public IntegerProperty p_idProperty() {
return p_id;
}
public StringProperty NameProperty() {
return Name;
}
}
My db looks like this:
CREATE TABLE person (p_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(30) NOT NULL);
How can I get the p_id or the Name of the row I clicked?
#FXML
private void pressTableAction() {
System.out.println("Selected index: " + table.getSelectionModel().getSelectedIndex());
System.out.println("Selected p_id: " + ????)
}

First, do not use raw types for your table and table columns. Your IDE should be generating lots of warnings for this. So you should do
#FXML
TableView<UserData> table ;
instead of the declaration you have. Similarly the columns should be declared with the appropriate types.
If your model class UserData follows the standard JavaFX properties pattern, it will have a getP_id() method, and you can do
UserData selected = table.getSelectionModel().getSelectedItem();
System.out.println("Selected p_id: "+selected.getP_id());

Related

Can't properly display data in tableView in JavaFX

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.

Why can't I select a checkbox in my tableview?

I have a javaFX 8 pane that contains a Piles TableView. When I select a Pile from the TableView, it queries a database and populates a second TableView with instances of LogExt. This second TableView includes a column of checkboxes mapped to the LogExt.selected boolean property.
When I run the application, I can't select any of the checkboxes.
LogExt:
public class LogExt {
private BooleanProperty selected = new SimpleBooleanProperty();
private Log log;
public LogExt(Log log) {
this.setSelected(false);
this.log = log;
}
public boolean isSelected() {
return selected.get();
}
public BooleanProperty selectedProperty() {
return selected;
}
public void setSelected(boolean selected) {
this.selected.set(selected);
}
public Log getLog() {
return log;
}
public void setLog(Log log) {
this.log = log;
}
}
The controller:
public class CustomOrderController {
#FXML
private RadioButton openRadio;
#FXML
private ToggleGroup stageGroup;
#FXML
private TableView<Pile> pileTableView;
#FXML
private TableColumn<Pile, String> pileNoCol;
#FXML
private TableColumn<Pile, String> speciesCol;
#FXML
private TableColumn<Pile, String> gradeCol;
#FXML
private TableColumn<Pile, String> logTypeCol;
#FXML
private TableColumn<Pile, String> pileStartCol;
#FXML
private TableView<LogExt> logTable;
#FXML
private TableColumn<LogExt, Boolean> selectedCol;
#FXML
private TableColumn<LogExt, String> logSpeciesCol;
#FXML
private TableColumn<LogExt, String> logGradeCol;
#FXML
private TableColumn<LogExt, String> lengthCol;
#FXML
private TableColumn<LogExt, String> diameterCol;
#FXML
private TableColumn<LogExt, String> footageCol;
#FXML
private TextField totalFootageField;
#FXML
private TextField selectedFootageField;
#FXML
private Button clearButton;
#FXML
private TextField reportNoField;
#FXML
private Button saveButton;
private ObservableList openPileList = null;
private ObservableList finishedPileList = null;
private final static Logger LOG = LoggerFactory.getLogger(CustomOrderController.class);
#FXML
protected void initialize() {
super.initialize();
// Set table columns to display proper values.
pileNoCol.setCellValueFactory(new PropertyValueFactory<>("pileNo"));
speciesCol.setCellValueFactory(param -> {
StringProperty stringProperty;
if (param.getValue().getSpecies() != null)
stringProperty = new SimpleStringProperty(param.getValue().getSpecies().getName());
else stringProperty = new SimpleStringProperty("All");
return stringProperty;
});
gradeCol.setCellValueFactory(param -> {
StringProperty grade;
if (param.getValue().getGrade() != null)
grade = new SimpleStringProperty(param.getValue().getGrade().getName());
else grade = new SimpleStringProperty("All");
return grade;
});
logTypeCol.setCellValueFactory(param -> {
StringProperty logType;
if (param.getValue().getLogType() != null)
logType = new SimpleStringProperty(param.getValue().getLogType().getName());
else logType = new SimpleStringProperty("All");
return logType;
});
pileStartCol.setCellValueFactory(param -> {
StringProperty startDate;
if (param.getValue().getPileStart() != null)
startDate = new SimpleStringProperty(
param.getValue().getPileStart().format(DATETIMEFORMATTER));
else startDate = null;
return startDate;
});
// Add listener to catch table selections.
pileTableView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> selectPile());
// Add listener to catch radio button selections.
stageGroup.selectedToggleProperty().addListener((
observable, oldValue, newValue) -> changeList());
// Ensure values entered in the limit/warning fields are acceptable.
reportNoField.setTextFormatter(new TextFormatter<>(INTEGERSTRINGCONVERTER
, 0, POSINTEGERFILTER));
selectedCol.setCellValueFactory(new PropertyValueFactory<>("selected"));
selectedCol.setCellFactory(CheckBoxTableCell.forTableColumn(selectedCol));
logSpeciesCol.setCellValueFactory(param ->
new SimpleStringProperty(param.getValue().getLog().getSpecies().getName()));
logGradeCol.setCellValueFactory(param ->
new SimpleStringProperty(param.getValue().getLog().getLogGrade().getName()));
lengthCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getDeductionLength())));
diameterCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getDeductionDiameter())));
footageCol.setCellValueFactory(param ->
new SimpleStringProperty(String.format("%d", param.getValue().getLog().getNetFootage())));
}
protected void refreshPane() {
// Get the list of piles.
openPileList = FXCollections.observableList(HibernateUtil.getProgramsCommonDB().
query("from Pile where pileEnd = '" + NODATETIME.format(QUERYDATETIMEFORMATTER) + "'"));
finishedPileList = FXCollections.observableList(HibernateUtil.getProgramsCommonDB().
query("from Pile where pileEnd > '" + NODATETIME.format(QUERYDATETIMEFORMATTER) +
"' and consumeStart = '" + NODATETIME.format(QUERYDATETIMEFORMATTER) + "'"));
changeList();
// Set buttons and fields off to start.
clear();
}
private void changeList() {
clear();
if (openRadio.isSelected()) pileTableView.setItems(openPileList);
else pileTableView.setItems(finishedPileList);
}
private void enableWidgets(boolean yes) {
clearButton.setDisable(!yes);
logTable.setDisable(!yes);
reportNoField.setDisable(!yes);
LOG.info("OpenRadio: {}, enable: {}", openRadio.isSelected(), yes);
saveButton.setDisable(true);
}
private void clearWidgets() {
pileTableView.getSelectionModel().clearSelection();
logTable.getItems().clear();
totalFootageField.clear();
selectedFootageField.clear();
reportNoField.clear();
}
#FXML
private void clear() {
clearWidgets();
enableWidgets(false);
}
private void selectPile() {
Pile currentPile = pileTableView.getSelectionModel().getSelectedItem();
if (currentPile != null) {
// Fill the logs list with logs from this pile that have not been consumed.
List oList = HibernateUtil.getLogsDB().query("from Log where pileID = "
+ currentPile.getId()
+ " and (consumeTime is null or consumeTime = '"
+ NODATETIME.format(QUERYDATETIMEFORMATTER) + "')");
List<LogExt> logList = new ArrayList<>();
oList.forEach(o -> {
LogExt logExt = new LogExt((Log) o);
logList.add(logExt);
});
totalFootageField.setText(String.format("%d", logList.stream()
.mapToInt(value -> value.getLog().getNetFootage())
.sum()));
logTable.setItems(FXCollections.observableList(logList));
enableWidgets(true);
}
}
}
You need to enable editing on your table.
logTable.setEditable(true);
possibly on your column as well
selectedCol.setEditable(true);

Tableview update database on edit

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);
}
}

Java FX TableView Database

I am building on Java FX application 3 weeks now and i have a problem i search things about that over the internet but i can't find the solution. I have to Populate Data on rows in a tableview i am getting data from database but i can't put it in the table i have this code that i use in order to take the data from Database.
public ObservableList<ObservableList> GetCustomerData(){
ObservableList<ObservableList> Data = FXCollections.observableArrayList();
try{
ConnectToDB();
DBStatement = DBConnection.createStatement();
DataRetrive = DBStatement.executeQuery("SELECT * FROM Customer");
while (DataRetrive.next()){
ObservableList<String> Row = FXCollections.observableArrayList();
Row.add(String.valueOf(DataRetrive.getInt(1)));
Row.add(DataRetrive.getString(2));
Row.add(DataRetrive.getString(3));
Row.add(DataRetrive.getString(4));
Row.add(DataRetrive.getString(5));
Row.add(DataRetrive.getString(6));
Row.add(DataRetrive.getString(7));
Row.add(DataRetrive.getString(8));
Row.add(DataRetrive.getString(9));
Data.add(Row);
}
CloseDB();
}catch(SQLException e){
e.printStackTrace();
}
return Data;
}
How can I add Data in table cells from this ObservableList?
It is good practice to have a separate class to CRUD operations:
public abstract class CustomerDML {
public static final String TABLE_NAME = "Customer";
QueryClass qc = new QueryClass();
public ObservableList<Map> getCustomerData() {
ObservableList<Map> productList = FXCollections.observableArrayList();
try {
qc.setPs(qc.getConn().prepareStatement("SELECT * FROM " + TABLE_NAME));
qc.setRs(qc.getPs().executeQuery());
while (qc.getRs().next()) {
Map<String, String> product = new HashMap<>();
product.put("cus_id", String.valueOf(qc.getRs().getInt("cus_id")));
product.put("name", qc.getRs().getString("name"));
product.put("age", String.valueOf(qc.getRs().getInt("age")));
product.put("telephone", qc.getRs().getString("telephone"));
productList.add(product);
}
return customerList;
} catch (SQLException ex) {
return null;
}
}
You can implement your QueryClass like below :
public class QueryClass {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
//private String query;
public QueryClass() {
conn = DBConnectionClass.myConnection();
}
//getters and setters
...
Lets assume the we have injected something like below to your controller from your fxml:
public class Customer_fxmlController extends CustomerDML implements Initializable {
#FXML
private TableView<Map> cusTable;
#FXML
private TableColumn idCol;
#FXML
private TableColumn nameCol;
#FXML
private TableColumn ageCol;
#FXML
private TableColumn telCol;
...
public void loadCustomers() {
idCol.setCellValueFactory(new MapValueFactory("cus_id"));
nameCol.setCellValueFactory(new MapValueFactory("name"));
ageCol.setCellValueFactory(new MapValueFactory("age"));
telCol.setCellValueFactory(new MapValueFactory("telephone"));
cusTable.setItems(getCustomerData());//Which returns a ObservableList<Map>
}

Set ComboBoxCell in TableView JavaFX

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.

Resources