TableView not showing items [duplicate] - user-interface

OK, new to java by several weeks, but have been programming for 30 years. The following code executes, but only the first column is showing anything. The data object is showing multiple rows of data, with fields of data that are filled in. I'm sure I'm missing something, and have looked through similar questions on here.
APVoucher_batchgridController.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author kmitchell
*/
public class APVoucher_batchgridController implements Initializable {
public TableView tblMainList;
public TableColumn colDateEntered;
public TableColumn colCreatedBy;
public TableColumn colDescription;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
public void opentables(ActionEvent event) {
Object forName = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("DateEntered"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("cDesc"));
colCreatedBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("CreatedBy"));
try {
// load the driver into memory
forName = Class.forName("jstels.jdbc.dbf.DBFDriver2");
} catch (ClassNotFoundException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = DriverManager.getConnection("jdbc:jstels:dbf:e:\\keystone-data\\keyfund\\seymour\\keyfund.dbc");
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (conn != null) {
try {
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
if (stmt != null) {
// execute a query
try {
ObservableList<Object> data = FXCollections.observableArrayList();
rs = stmt.executeQuery("SELECT denteredon, cdesc, ccreatedby FROM apvbatch WHERE ldeleted = false ORDER BY denteredon DESC");
while (rs.next()) {
String enteredon = rs.getString("denteredon");
String desc = rs.getString("cdesc");
String createdby = rs.getString("ccreatedby");
sresult row = new sresult(createdby, enteredon, desc);
data.add(row);
}
tblMainList.setItems(data);
tblMainList.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(APVoucher_batchgridController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class sresult {
private String DateEntered;
private String EnteredBy;
private String cDesc;
public sresult(String T, String d, String c) {
this.EnteredBy = T;
this.DateEntered = d;
this.cDesc = c;
}
public String getEnteredBy() {
return EnteredBy;
}
public void setEnteredBy(String T) {
EnteredBy = T;
}
public String getDateEntered() {
return DateEntered;
}
public void setDateEntered(String d) {
DateEntered = d;
}
public String getcDesc() {
return cDesc;
}
public void setcDesc(String c) {
cDesc = c;
}
}
}
and APVoucher_batchgrid.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" fx:id="batchlistform" prefHeight="400.0" prefWidth="600.0" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="keystone.APVoucher_batchgridController">
<children>
<BorderPane layoutX="0.0" layoutY="0.0" prefHeight="400.0" prefWidth="600.0">
<center>
<AnchorPane prefHeight="-1.0" prefWidth="-1.0">
<children>
<Pane layoutX="0.0" layoutY="0.0" prefHeight="53.0" prefWidth="580.0">
<children>
<Label layoutX="7.0" layoutY="9.0" prefWidth="202.0" text="AP Vouchers Batch List">
<font>
<Font name="System Bold" size="14.0" />
</font>
</Label>
<Button fx:id="btnClose" cancelButton="true" layoutX="513.0" layoutY="27.0" mnemonicParsing="false" text="Close" />
<Button id="btnClose" fx:id="apvRefresh" cancelButton="true" layoutX="185.0" layoutY="27.0" mnemonicParsing="false" onAction="#opentables" text="Refresh" />
</children>
</Pane>
<TableView fx:id="tblMainList" layoutX="0.0" layoutY="53.0" prefHeight="323.0" prefWidth="580.0">
<columns>
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="91.0" text="Date Entered" fx:id="colDateEntered" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="100.0" text="Created By" fx:id="colCreatedBy" />
<TableColumn maxWidth="5000.0" minWidth="10.0" prefWidth="261.0" text="Description" fx:id="colDescription" />
</columns>
</TableView>
</children>
</AnchorPane>
</center>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</BorderPane>
</children>
<stylesheets>
<URL value="#apvoucher_batchgrid.css" />
</stylesheets>
</AnchorPane>
THANK YOU for the answer. Way to many years in case insensitive languages. This has been a quick and dirty exercise for me to learn java and the latest & greatest stuff or as I like to say New Exciting Technology (NExT!)
For anyone looking at the answer and still not completely clued in, here are the changes that made the code work properly.
colDateEntered.setCellValueFactory(new PropertyValueFactory<sresult, String>("Denteredon"));
colDescription.setCellValueFactory(new PropertyValueFactory<sresult, String>("CDesc"));
colEnteredBy.setCellValueFactory(new PropertyValueFactory<sresult, String>("Ccreatedby"));
public class sresult {
private String Denteredon;
private String Ccreatedby;
private String CDesc;
public sresult(String T, String d, String c) {
this.Ccreatedby = T;
this.Denteredon = d;
this.CDesc = c;
}
public String getCcreatedby() {
return Ccreatedby;
}
public void setCreatedby(String T) {
Ccreatedby = T;
}
public String getDenteredon() {
return Denteredon;
}
public void setDenteredon(String d) {
Denteredon = d;
}
public String getCDesc() {
return CDesc;
}
public void setCDesc(String c) {
CDesc = c;
}
}
}

This question is really a duplicate of: Javafx PropertyValueFactory not populating Tableview, but I'll specifically address your specific case, so it's clear.
Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
How do you use a JavaFX TableView with java records?
demonstrates replacing PropertyValueFactory with lambda expressions.
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
Background
PropertyValueFactory uses reflection to determine the methods to get and set data values as well as to retrieve bindable properties from your model class. The pattern followed is:
PropertyValueType getName()
void setName(PropertyValueType value)
PropertyType nameProperty()
Where "name" is the string specified in the PropertyValueFactory constructor. The first letter of the property name in the getter and setter is capitalized (by java bean naming convention).
Why your application doesn't work
You have these three expressions:
new PropertyValueFactory<sresult, String>("DateEntered")
new PropertyValueFactory<sresult, String>("cDesc")
new PropertyValueFactory<sresult, String>("CreatedBy")
For your sample properties, the PropertyValueFactory will look for these methods:
"DateEntered" => getDateEntered()
"cDesc" => getCDesc()
"CreatedBy" => getCreatedBy()
And you have these three getters on your sresult class:
getDateEntered()
getcDesc()
getEnteredBy()
Only getDateEntered() is going to be picked up by the PropertyValueFactory because that is the only matching method defined in the sresult class.
Advice
You will have to adopt Java standards if you want the reflection in PropertyValueFactory to work (the alternative is to not use the PropertyValueFactory and instead write your own cell factories from scratch).
Adopting Java camel case naming conventions also makes it easier for Java developers to read your code.

Some times columns doesn't show data because of column names. eg,
new PropertyValueFactory<sresult, String>("cDesc")
and getter is getcDesc cDesc column may not display data. If you change code to
new PropertyValueFactory<sresult, String>("CDesc")
and getter is getCDesc CDesc column may display data.

For anyone else who still wasn't getting it after going through the above, my problem was that I wasn't specifying my setters with the "public final" designation.

Related

How to refresh a TableView after updating it from another scene (and another controller)?

I have a TableView that contains entries from a database and a separate window for entering a new entry with a separate controller. The problem is that when I add a record to the database, the table scene controller doesn't know that there has been a change and the TableView is only updated after the application is restarted. How to create this connection between the controllers so that the TableView is updated immediately?
Main class.
public class ExampleApplication extends Application {
#Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("tableView.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 700, 400);
stage.setTitle("ExampleApp");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Scene controller with a table where entries are displayed.
public class TableController {
#FXML
private Button addEntryButton;
#FXML
private TableColumn<userEntry, String> entryColumn;
#FXML
private TableView<userEntry> table;
ObservableList<userEntry> userEntries = FXCollections.observableArrayList();
#FXML
private void initialize() {
table.getItems().clear();
getAllEntriesFromDbToList();
entryColumn.setCellValueFactory(new PropertyValueFactory<userEntry, String>("entryName"));
table.setItems(userEntries);
addEntryButton.setOnAction(event -> {
openNewScene("/com/example/addNewEntryDialogue.fxml");
});
}
private void getAllEntriesFromDbToList() {
ResultSet rs = new DatabaseHandler().getEntriesTableFromDb();
try {
while (rs.next()) {
userEntries.add(new userEntry(rs.getString("entryName")
));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void openNewScene(String window) {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(window));
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Parent root = loader.getRoot();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}
}
Dialog window controller for adding a new entry.
public class DialogueController {
#FXML
private Button inputNewEntryCancelButton;
#FXML
private Button inputNewEntryOkButton;
#FXML
private TextField inputNewEntryTextField;
#FXML
void initialize() {
inputNewEntryOkButton.setOnAction(event -> {
addNewEntryToDbTable(inputNewEntryTextField.getText());
((Node) event.getSource()).getScene().getWindow().hide();
});
inputNewEntryCancelButton.setOnAction(event -> {
((Node) event.getSource()).getScene().getWindow().hide();
});
}
private void addNewEntryToDbTable(String entryName) {
DatabaseHandler dbHandler = new DatabaseHandler();
userEntry newEntry = new userEntry(entryName);
dbHandler.addEntryToDb(newEntry);
}
}
Model. Entry class.
public class userEntry {
private String entryName;
public userEntry(String entryName) {
this.entryName = entryName;
}
public String getEntryName() {
return entryName;
}
public void setEntryName(String entryName) {
this.entryName = entryName;
}
}
Model. Data base handler class.
public class DatabaseHandler extends Configs {
Connection dbConnection;
public Connection getDbConnection() throws ClassNotFoundException, SQLException {
String connectionString = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName;
Class.forName("com.mysql.cj.jdbc.Driver");
dbConnection = DriverManager.getConnection(connectionString, dbUser, dbPass);
return dbConnection;
}
public void addEntryToDb(userEntry task) {
String insert = "INSERT INTO " + Const.ENTRIES_TABLE + "(" +
Const.ENTRIES_ENTRY_NAME + ")" +
"VALUES(?)";
try {
PreparedStatement prSt = getDbConnection().prepareStatement(insert);
prSt.setString(1, task.getEntryName());
prSt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public ResultSet getEntriesTableFromDb() {
ResultSet resSet = null;
String select = "SELECT * FROM " + Const.ENTRIES_TABLE;
try {
resSet = getDbConnection().createStatement().executeQuery(select);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return resSet;
}
}
View. Table scene FXML. (tableView.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane prefHeight="386.0" prefWidth="248.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/18" fx:controller="com.example.tableviewtesting.TableController">
<opaqueInsets>
<Insets />
</opaqueInsets>
<bottom>
<TableView fx:id="table" maxHeight="-Infinity" prefHeight="329.0" prefWidth="248.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="entryColumn" prefWidth="247.0" text="Entries" />
</columns>
</TableView>
</bottom>
<top>
<Button fx:id="addEntryButton" mnemonicParsing="false" text="Add entry">
<BorderPane.margin>
<Insets left="10.0" top="10.0" />
</BorderPane.margin>
</Button>
</top>
</BorderPane>
View. Dialog scene FXML. (addNewEntryDialogue.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="100.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.tableviewtesting.DialogueController">
<children>
<Label alignment="CENTER" layoutX="8.0" layoutY="18.0" prefHeight="36.0" prefWidth="70.0" text="Entry name:" />
<TextField fx:id="inputNewEntryTextField" layoutX="82.0" layoutY="16.0" prefHeight="40.0" prefWidth="208.0" />
<Button fx:id="inputNewEntryCancelButton" layoutX="156.0" layoutY="65.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="134.0" text="Cancel" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="156.0" AnchorPane.rightAnchor="10.0" />
<Button fx:id="inputNewEntryOkButton" layoutX="10.0" layoutY="70.0" mnemonicParsing="false" prefHeight="25.0" prefWidth="134.0" text="Create new entry" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="10.0" AnchorPane.rightAnchor="156.0" />
</children>
</AnchorPane>
You did not produce an MCVE, so I am going to try to guess based on your limited code.
Here is a method that deletes a Person from an SQLite database.
The following code accepts the person that needs to be deleted in the DB and returns a boolean based on if the person was successfully deleted from the DB or not.
dBHandler.deletePerson(person)
The following code demonstrates using the boolean return value to determine what should happen based on if true or false is returned.
if (dBHandler.deletePerson(person)) {
//delete the `Person` from the `TableView`.
} else {
//Alert the user that the `Person` was not deleted from the DB.
//Do not delete the `Person` from the `TableView`.
}
Actual Code Snippet
#FXML
private void handleBtnDeletePerson(ActionEvent actionEvent) {
Person person = tvMain.getSelectionModel().getSelectedItem();
if (dBHandler.deletePerson(person)) {
//Update TableView
tvMain.getItems().remove(person); //Remove Person from the TableView
lblLastAction.setText(person.getFirstName() + " deleted!");
} else {
lblLastAction.setText(person.getFirstName() + " failed to delete!");
}
}
Full Code Link: https://github.com/sedj601/SQLitePersonTableViewExample
If you have a long-running task, see the following code: https://github.com/sedj601/SQLitePersonTableViewExampleUsingTask.
Warning: this is old code and may be lacking! Hopefully, the ideas are sound, though!

JavaFX custom MasterDetail pane

I have created a custom Master-Detail pane for my project, where i use a split pane, in each i have two Anchor Panes. In one there is a TableView filled with Users (ObservableList). On each row (User) i have implemented a ChangeListener
table.getSelectionModel().selectedItemProperty().addListener(listElementChangeListener());
when the row is selected, i pass the UserObject for my DetailPane, and visualize User data in TextFields as detail. I have implemented controls, to understand if the User is under modification in Detail, and if so i would like to prevent a row change in my TableView. I tried to remove the ChangeListener from the TableView when i modify the User, but it dosent work well. I'm thinking of a solution like setting the focus and holding it on the row until i cancel or save the User modified.
Is there any nice solutions?
Thanks for your help.
I would probably approach this a little differently. I would bind the controls in the "detail view" bidirectionally to the properties in the User object. That way they will be updated in the object (and the table) as the user edits them. If you like, you can also provide a "cancel" button to revert to the previous values.
Here's a complete solution that uses this approach:
User.java:
package usermasterdetail;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class User {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final BooleanProperty admin = new SimpleBooleanProperty();
public User(String firstName, String lastName, boolean admin) {
setFirstName(firstName);
setLastName(lastName);
setAdmin(admin);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final BooleanProperty adminProperty() {
return this.admin;
}
public final boolean isAdmin() {
return this.adminProperty().get();
}
public final void setAdmin(final boolean admin) {
this.adminProperty().set(admin);
}
}
DataModel.java:
package usermasterdetail;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class DataModel {
private final ObservableList<User> userList = FXCollections.observableArrayList(
new User("Jacob", "Smith", false),
new User("Isabella", "Johnson", true),
new User("Ethan", "Williams", false),
new User("Emma", "Jones", true),
new User("Michael", "Brown", true)
);
private final ObjectProperty<User> currentUser = new SimpleObjectProperty<>();
public final ObjectProperty<User> currentUserProperty() {
return this.currentUser;
}
public final User getCurrentUser() {
return this.currentUserProperty().get();
}
public final void setCurrentUser(final User currentUser) {
this.currentUserProperty().set(currentUser);
}
public ObservableList<User> getUserList() {
return userList;
}
}
TableController.java:
package usermasterdetail;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
public class TableController {
#FXML
private TableView<User> table ;
#FXML
private TableColumn<User, String> firstNameColumn ;
#FXML
private TableColumn<User, String> lastNameColumn ;
#FXML
private TableColumn<User, Boolean> adminColumn ;
private DataModel model ;
public void initialize() {
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
adminColumn.setCellValueFactory(cellData -> cellData.getValue().adminProperty());
adminColumn.setCellFactory(CheckBoxTableCell.forTableColumn(adminColumn));
}
public void setDataModel(DataModel dataModel) {
if (model != null) {
model.currentUserProperty().unbind();
}
this.model = dataModel ;
dataModel.currentUserProperty().bind(table.getSelectionModel().selectedItemProperty());
table.setItems(model.getUserList());
}
}
UserEditorController.java:
package usermasterdetail;
import javafx.beans.value.ChangeListener;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
public class UserEditorController {
#FXML
private TextField firstNameField ;
#FXML
private TextField lastNameField ;
#FXML
private CheckBox adminCheckBox ;
private String cachedFirstName ;
private String cachedLastName ;
private boolean cachedAdmin ;
private ChangeListener<User> userListener = (obs, oldUser, newUser) -> {
if (oldUser != null) {
firstNameField.textProperty().unbindBidirectional(oldUser.firstNameProperty());
lastNameField.textProperty().unbindBidirectional(oldUser.lastNameProperty());
adminCheckBox.selectedProperty().unbindBidirectional(oldUser.adminProperty());
}
if (newUser == null) {
firstNameField.clear();
lastNameField.clear();
adminCheckBox.setSelected(false);
} else {
firstNameField.textProperty().bindBidirectional(newUser.firstNameProperty());
lastNameField.textProperty().bindBidirectional(newUser.lastNameProperty());
adminCheckBox.selectedProperty().bindBidirectional(newUser.adminProperty());
cachedFirstName = newUser.getFirstName();
cachedLastName = newUser.getLastName();
cachedAdmin = newUser.isAdmin();
}
};
private DataModel model ;
public void setDataModel(DataModel dataModel) {
if (this.model != null) {
this.model.currentUserProperty().removeListener(userListener);
}
this.model = dataModel ;
this.model.currentUserProperty().addListener(userListener);
}
#FXML
private void cancel() {
firstNameField.setText(cachedFirstName);
lastNameField.setText(cachedLastName);
adminCheckBox.setSelected(cachedAdmin);
}
}
Table.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TableColumn?>
<StackPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="usermasterdetail.TableController">
<TableView fx:id="table">
<columns>
<TableColumn fx:id="firstNameColumn" text="First Name"/>
<TableColumn fx:id="lastNameColumn" text="Last Name"/>
<TableColumn fx:id="adminColumn" text="Administrator"/>
</columns>
</TableView>
</StackPane>
UserEditor.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="usermasterdetail.UserEditorController"
hgap="5" vgap="5" alignment="CENTER">
<columnConstraints>
<ColumnConstraints halignment="RIGHT" hgrow="NEVER"/>
<ColumnConstraints halignment="LEFT" hgrow="SOMETIMES"/>
</columnConstraints>
<padding>
<Insets top="5" left="5" bottom="5" right="5"/>
</padding>
<Label text="First Name:" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
<Label text="Last Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<Label text="Admin Priviliges:" GridPane.columnIndex="0" GridPane.rowIndex="2"/>
<TextField fx:id="firstNameField" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<TextField fx:id="lastNameField" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<CheckBox fx:id="adminCheckBox" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<Button text="Cancel" onAction="#cancel" GridPane.columnIndex="0" GridPane.rowIndex="3" GridPane.columnSpan="2"
GridPane.halignment="CENTER"/>
</GridPane>
MainController.java:
package usermasterdetail;
import javafx.fxml.FXML;
public class MainController {
#FXML
private TableController tableController ;
#FXML
private UserEditorController editorController ;
private final DataModel model = new DataModel();
public void initialize() {
tableController.setDataModel(model);
editorController.setDataModel(model);
}
}
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.SplitPane?>
<SplitPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="usermasterdetail.MainController">
<items>
<fx:include fx:id="table" source="Table.fxml"/>
<fx:include fx:id="editor" source="UserEditor.fxml"/>
</items>
</SplitPane>
And finally Main.java:
package usermasterdetail;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
primaryStage.setScene(new Scene(FXMLLoader.load(getClass().getResource("Main.fxml")), 800, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
If you prefer the user experience you described, you can (as #SSchuette describes in the comments), just bind the table's disable property to the modifying property. This will prevent the user from changing the selection while the data is being edited (i.e. is not consistent with the data in the table). For this you just need the modifying property in the model:
package usermasterdetail;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class DataModel {
private final ObservableList<User> userList = FXCollections.observableArrayList(
new User("Jacob", "Smith", false),
new User("Isabella", "Johnson", true),
new User("Ethan", "Williams", false),
new User("Emma", "Jones", true),
new User("Michael", "Brown", true)
);
private final ObjectProperty<User> currentUser = new SimpleObjectProperty<>();
private final BooleanProperty modifying = new SimpleBooleanProperty();
public final ObjectProperty<User> currentUserProperty() {
return this.currentUser;
}
public final usermasterdetail.User getCurrentUser() {
return this.currentUserProperty().get();
}
public final void setCurrentUser(final usermasterdetail.User currentUser) {
this.currentUserProperty().set(currentUser);
}
public ObservableList<User> getUserList() {
return userList;
}
public final BooleanProperty modifyingProperty() {
return this.modifying;
}
public final boolean isModifying() {
return this.modifyingProperty().get();
}
public final void setModifying(final boolean modifying) {
this.modifyingProperty().set(modifying);
}
}
then in the table controller you can bind the disable property to it:
package usermasterdetail;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
public class TableController {
#FXML
private TableView<User> table ;
#FXML
private TableColumn<User, String> firstNameColumn ;
#FXML
private TableColumn<User, String> lastNameColumn ;
#FXML
private TableColumn<User, Boolean> adminColumn ;
private DataModel model ;
public void initialize() {
firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
adminColumn.setCellValueFactory(cellData -> cellData.getValue().adminProperty());
adminColumn.setCellFactory(CheckBoxTableCell.forTableColumn(adminColumn));
}
public void setDataModel(DataModel dataModel) {
if (model != null) {
model.currentUserProperty().unbind();
}
this.model = dataModel ;
dataModel.currentUserProperty().bind(table.getSelectionModel().selectedItemProperty());
table.setItems(model.getUserList());
table.disableProperty().bind(model.modifyingProperty());
}
}
The only place there is a bit of work to do is to make sure the modifying property is set to true any time the data are not in sync (though it sounds like you have already done this):
package usermasterdetail;
import javafx.beans.value.ChangeListener;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
public class UserEditorController {
#FXML
private TextField firstNameField ;
#FXML
private TextField lastNameField ;
#FXML
private CheckBox adminCheckBox ;
private DataModel model ;
private ChangeListener<Object> modifyingListener = (obs, oldValue, newValue) -> {
if (model != null) {
if (model.getCurrentUser() == null) {
model.setModifying(false);
} else {
model.setModifying(! (model.getCurrentUser().getFirstName().equals(firstNameField.getText())
&& model.getCurrentUser().getLastName().equals(lastNameField.getText())
&& model.getCurrentUser().isAdmin() == adminCheckBox.isSelected()));
}
}
};
private ChangeListener<User> userListener = (obs, oldUser, newUser) -> {
if (oldUser != null) {
oldUser.firstNameProperty().removeListener(modifyingListener);
oldUser.lastNameProperty().removeListener(modifyingListener);
oldUser.adminProperty().removeListener(modifyingListener);
}
if (newUser == null) {
firstNameField.clear();
lastNameField.clear();
adminCheckBox.setSelected(false);
} else {
firstNameField.setText(newUser.getFirstName());
lastNameField.setText(newUser.getLastName());
adminCheckBox.setSelected(newUser.isAdmin());
newUser.firstNameProperty().addListener(modifyingListener);
newUser.lastNameProperty().addListener(modifyingListener);
newUser.adminProperty().addListener(modifyingListener);
}
};
public void setDataModel(DataModel dataModel) {
if (this.model != null) {
this.model.currentUserProperty().removeListener(userListener);
}
this.model = dataModel ;
this.model.currentUserProperty().addListener(userListener);
}
public void initialize() {
firstNameField.textProperty().addListener(modifyingListener);
lastNameField.textProperty().addListener(modifyingListener);
adminCheckBox.selectedProperty().addListener(modifyingListener);
}
#FXML
private void cancel() {
if (model != null) {
firstNameField.setText(model.getCurrentUser().getFirstName());
lastNameField.setText(model.getCurrentUser().getLastName());
adminCheckBox.setSelected(model.getCurrentUser().isAdmin());
}
}
#FXML
private void update() {
if (model != null && model.getCurrentUser() != null) {
model.getCurrentUser().setFirstName(firstNameField.getText());
model.getCurrentUser().setLastName(lastNameField.getText());
model.getCurrentUser().setAdmin(adminCheckBox.isSelected());
}
}
}
This solution requires an additional button to force the update in the data (and table):
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.HBox?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="usermasterdetail.UserEditorController"
hgap="5" vgap="5" alignment="CENTER">
<columnConstraints>
<ColumnConstraints halignment="RIGHT" hgrow="NEVER"/>
<ColumnConstraints halignment="LEFT" hgrow="SOMETIMES"/>
</columnConstraints>
<padding>
<Insets top="5" left="5" bottom="5" right="5"/>
</padding>
<Label text="First Name:" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
<Label text="Last Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<Label text="Admin Priviliges:" GridPane.columnIndex="0" GridPane.rowIndex="2"/>
<TextField fx:id="firstNameField" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<TextField fx:id="lastNameField" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<CheckBox fx:id="adminCheckBox" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<HBox spacing="5" alignment="CENTER" GridPane.columnIndex="0" GridPane.rowIndex="3" GridPane.columnSpan="2">
<Button text="Update" onAction="#update"/>
<Button text="Cancel" onAction="#cancel"/>
</HBox>
</GridPane>

javafx8 TableView Multiselection returns one of the selected items as null

TableView multi selection returns one of the selected objects as null. This doesn't happen every time but happens most of the times when i try to select two rows in the table.similar to the issue defined in this question
Best way of reproducing the issue is , try selecting two sequential rows .
FXML :
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.cell.PropertyValueFactory?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.StackPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.test.controller.TestController">
<children>
<TableView fx:id="personsTable" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="35.0">
<placeholder>
<Label text="" />
</placeholder>
<columns>
<TableColumn text="Name">
<cellValueFactory>
<PropertyValueFactory property="name" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Address">
<cellValueFactory>
<PropertyValueFactory property="address" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Course">
<cellValueFactory>
<PropertyValueFactory property="course" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Country">
<cellValueFactory>
<PropertyValueFactory property="country" />
</cellValueFactory>
</TableColumn>
</columns>
</TableView>
</children>
</AnchorPane>
Controller :
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import com.test.model.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableView;
public class TestController implements Initializable {
#FXML
TableView<Person> personsTable = new TableView<Person>();
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
MenuItem combine = new MenuItem("Select");
combine.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
List<Person> selectedPersons = new ArrayList<Person>(
personsTable.getSelectionModel().getSelectedItems());
for (Person person : selectedPersons) {
System.out.println(" the object is " + person);
}
}
});
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().add(combine);
personsTable.setContextMenu(contextMenu);
personsTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
personsTable.setItems(getPendingOrders());
}
public ObservableList<Person> getPendingOrders() {
ObservableList<Person> persons = FXCollections.observableArrayList();
for (int i = 0; i < 100; i++) {
Person person = new Person();
person.setName("Name" + i);
person.setAddress("Address" + i);
person.setCountry("Country" + i);
person.setCourse("Course" + i);
persons.add(person);
}
return persons;
}
}
Model :
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
private String name;
private String address;
private String country;
private String course;
}
1: add a default cell factory to your TableView
2: override either updateItem or updateIndex
hope it helpls

Unable to insert values into tableview - JavaFx

I am new to JavaFx and I am trying to create a tableview and fxml is created using scene builder. If I run the program, the table is not getting the values. I found that this question is somehow matching with my requirement (javaFX 2.2 - Not able to populate table from Controller), but my code is matching with that too. But still I am not able to get the values in the table.
I have referenced the following video : http://www.youtube.com/watch?v=HiZ-glk9_LE
My code is as follows,
MainView.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MainView extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
AnchorPane page = FXMLLoader.load(MainView.class.getResource("MainView.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Sample Window");
primaryStage.setResizable(false);
primaryStage.show();
} catch (Exception e) {
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="controller.MainViewController">
<children>
<SplitPane dividerPositions="0.535175879396985" focusTraversable="true" orientation="VERTICAL" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<TableView fx:id="tableID" prefHeight="210.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" />
<TableColumn prefWidth="100.0" text="Date" fx:id="tDate" />
<TableColumn prefWidth="200.0" text="Name" fx:id="tName" />
<TableColumn prefWidth="75.0" text="Price" fx:id="tPrice" />
</columns>
</TableView>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0" />
</items>
</SplitPane>
</children>
</AnchorPane>
MainViewController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import model.Table;
/**
* FXML Controller class
*
*/
public class MainViewController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML
TableView<Table> tableID;
#FXML
TableColumn<Table, Integer> tID;
#FXML
TableColumn<Table, String> tName;
#FXML
TableColumn<Table, String> tDate;
#FXML
TableColumn<Table, String> tPrice;
int iNumber = 1;
ObservableList<Table> data =
FXCollections.observableArrayList(
new Table(iNumber++, "Dinesh", "12/02/2013", "20"),
new Table(iNumber++, "Vignesh", "2/02/2013", "40"),
new Table(iNumber++, "Satheesh", "1/02/2013", "100"),
new Table(iNumber++, "Dinesh", "12/02/2013", "16"));
#Override
public void initialize(URL url, ResourceBundle rb) {
// System.out.println("called");
tID.setCellValueFactory(new PropertyValueFactory<Table, Integer>("rID"));
tName.setCellValueFactory(new PropertyValueFactory<Table, String>("rName"));
tDate.setCellValueFactory(new PropertyValueFactory<Table, String>("rDate"));
tPrice.setCellValueFactory(new PropertyValueFactory<Table, String>("rPrice"));
tableID.setItems(data);
}
}
Table.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Table {
SimpleIntegerProperty rID;
SimpleStringProperty rName;
SimpleStringProperty rDate;
SimpleStringProperty rPrice;
public Table(int rID, String rName, String rDate, String rPrice) {
this.rID = new SimpleIntegerProperty(rID);
this.rName = new SimpleStringProperty(rName);
this.rDate = new SimpleStringProperty(rDate);
this.rPrice = new SimpleStringProperty(rPrice);
System.out.println(rID);
System.out.println(rName);
System.out.println(rDate);
System.out.println(rPrice);
}
public Integer getrID() {
return rID.get();
}
public void setrID(Integer v) {
this.rID.set(v);
}
public String getrDate() {
return rDate.get();
}
public void setrDate(String d) {
this.rDate.set(d);
}
public String getrName() {
return rName.get();
}
public void setrName(String n) {
this.rDate.set(n);
}
public String getrPrice() {
return rPrice.get();
}
public void setrPrice(String p) {
this.rPrice.set(p);
}
}
Thanks in advance.
In a Table.java change all getters and setters names,
change getr* to getR*
change setr* to setR*
Thanks to #Uluk Biy. Whatever he mentioned, that needs to be changed and I found that I missed the <cellValueFactory> and <PropertyValueFactory> tags under the <TableColumn> tag for each columns in the FXML file which is as follows,
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" >
<cellValueFactory>
<PropertyValueFactory property="tID" />
</cellValueFactory>
</TableColumn>
Similar to this, all columns need to be updated like this.
After this change, the code is working fine. I am able to add the values into the row. :)

updateItem's second param have never be false in javafx2

I use javafx2 control TableView to dispay records in the database(I have 20 records now).
And when display the record,I want to add button in each row.
so I search lots of article use google,and write some code below.
the key code is:
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
I debug this code,the param "empty" would never be "false",
so the button would never be display in the table view,
can anyone help me? thanks
below is the complete code(java and fxml):
java:
package com.turbooo.restaurant.interfaces.javafx;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import com.turbooo.restaurant.domain.Customer;
import com.turbooo.restaurant.domain.CustomerRepository;
import com.turbooo.restaurant.interfaces.facade.dto.CustomerDto;
import com.turbooo.restaurant.interfaces.facade.dto.assembler.CustomerDtoAssembler;
import com.turbooo.restaurant.util.ContextHolder;
import com.turbooo.restaurant.util.UTF8Control;
public class CustomerController implements Initializable {
#FXML
private TableView<CustomerDto> customerTableView;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
TableColumn<CustomerDto, Long> idCol = new TableColumn<CustomerDto, Long>("id");
idCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
TableColumn<CustomerDto, String> nameCol = new TableColumn<CustomerDto, String>("name");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,String>("name")
);
TableColumn<CustomerDto, String> birthdayCol = new TableColumn<CustomerDto, String>("birthday");
birthdayCol.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<CustomerDto, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<CustomerDto, String> customer) {
if (customer.getValue() != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new SimpleStringProperty(sdf.format(customer.getValue().getBirthday()));
} else {
return new SimpleStringProperty("");
}
}
});
TableColumn<CustomerDto, Long> actionCol = new TableColumn<CustomerDto, Long>("action");
actionCol.setCellFactory(
new Callback<TableColumn<CustomerDto,Long>, TableCell<CustomerDto,Long>>() {
#Override
public TableCell<CustomerDto, Long> call(TableColumn<CustomerDto, Long> arg0) {
final TableCell<CustomerDto, Long> cell = new TableCell<CustomerDto, Long>() {
#Override
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
return cell;
}
});
//TODO add button column
customerTableView.getColumns().addAll(idCol, nameCol, birthdayCol, actionCol);
loadData();
}
public void loadData() {
CustomerRepository cusRepo = (CustomerRepository)ContextHolder.getContext().getBean("customerRepository");
List<Customer> customers = cusRepo.findAll();
CustomerDtoAssembler customerDTOAssembler = new CustomerDtoAssembler();
List<CustomerDto> customerDtos = customerDTOAssembler.toDTOList(customers);
ObservableList<CustomerDto> data = FXCollections.observableArrayList(customerDtos);
customerTableView.setItems(data);
}
public void showNewDialog(ActionEvent event) {
ResourceBundle resourceBundle = ResourceBundle.getBundle(
"com/turbooo/restaurant/interfaces/javafx/customer_holder",
new UTF8Control());
Parent container = null;
try {
container = FXMLLoader.load(
getClass().getResource("customer_holder.fxml"),
resourceBundle);
} catch (IOException e) {
e.printStackTrace();
}
container.setUserData(this); //pass the controller, so can access LoadData function in other place later
Scene scene = new Scene(container, 400, 300);
Stage stage = new Stage();
stage.setScene(scene);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane prefHeight="345.0" prefWidth="350.0" xmlns:fx="http://javafx.com/fxml" fx:controller="com.turbooo.restaurant.interfaces.javafx.CustomerController">
<center>
<TableView fx:id="customerTableView" prefHeight="200.0" prefWidth="200.0" />
</center>
<top>
<HBox alignment="CENTER_LEFT" prefHeight="42.0" prefWidth="350.0">
<children>
<Button text="new" onAction="#showNewDialog"/>
<Separator prefHeight="25.0" prefWidth="13.0" visible="false" />
<Button text="modify" />
<Separator prefHeight="25.0" prefWidth="15.0" visible="false" />
<Button text="delete" />
</children>
</HBox>
</top>
</BorderPane>
You haven't set a cellValueFactory for your action column, so it is always empty.
A simple way to do this is just to set the cell value to the id of the record.
actionCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
Additionally, I created a simple example for creating a table with Add buttons in it, which you could reference if needed.

Resources