Updated: Dynamic TableView Data From Database

Updated in: Aug 5, 2014 @ 12:50 by Narayan [This update is compatible with new Java 8 codes modified]

Hello, Today I’m going to show the demo of how to display the exact database data in JavaFX 2.0 from TableView. I call this TableView as Dynamic TableView because the tableview automatically manages the columns and rows.

Requirements of this demo:

Database Structure
This below give the structure of database table I used for sample.

 

JavaFX 2.0 SourceCode
Main GUIClass

This class consists all the GUI Components and the data are being extracted from database

Here I used ObservableList< ObservableList > ‘data’ for keeping the records so that I could add data of Rows and Columns.The above class makes a dynamic TableView extracted data from Database.

Database Connectivity Class

In above class the url,user,pass may varies according to your mysql configuration.

Output:

TableView From Database

Here you go the output depends upon the database queries.

 

All the source code are published in a github repository : https://github.com/privatejava/javafx-dynamic-tableview

Don’t hesitate on commenting your views.
Thanks for viewing Hava a 🙂 good day.

163 thoughts on “Updated: Dynamic TableView Data From Database”

  1. Hi Tan,
    Sorry for late but I was on the holiday.If you are planning to make things editable to directly on database then you will need to use different approach. May be you can use JPA or normal JDBC technology and bind the column wise data in ObservableList. As ObservableList is directly binded to the TableView Column Data.

  2. Hi just wanted to give you a quick heads up
    and let you know a few of the

    images aren’t loading correctly. I’m not sure why but I think its a linking issue.
    I’ve tried it in

    two different internet browsers and both show the same outcome.

  3. hello,I want to do the same as your program but I want to use scene builder to build my TableView. .. actually I tried It but It doesn’t work for me….could you please give me some guidlines

  4. Is that article correct for JavaFX 2 and Java 8 ??
    If not a new version would be welcome indeed…

  5. Pingback: greenprint.zendesk.com

  6. Thank you for this article.Helped me a lot fixing my duplicate row entry.Callback here saved me

  7. @FXML //TbaleView created by scenebuilder.
    private TableView tblBrand;
    private ObservableList brandObsrList;

    //following is called on button action event

    private void populateTable()
    {
    try
    {
    classBrand brandObj = new classBrand();
    ResultSet rs = null;
    rs = brandObj.getlBrands();

    /**
    * ******************************
    * Data added to ObservableList * ******************************
    */
    brandObsrList = FXCollections.observableArrayList();

    while (rs.next())
    {
    //Iterate Row
    ObservableList row = FXCollections.observableArrayList();

    // row.add(0, String.valueOf(rs.getInt(“brandId”)));
    row.add(1, rs.getString(“brandName”));

    brandObsrList.add(row);

    }
    //FINALLY ADDED TO TableView
    tblBrand.setItems(brandObsrList);

    System.out.println(“tblBrand ” + tblBrand.getItems());
    /* it prints the values as
    brandObsrList [BRAND, BRAND111, BRAND6, BRAND8, MUMABAI, OTHERS1, RFL]
    */

    }
    catch (Exception e)
    {
    e.printStackTrace();
    System.out.println(“Error on Building Data”);
    }

    }

    But tableView doesnot shows any records.However the looks of tableview is changed and clicking on rows after 7-8 results in exception…

    Kindly help.

  8. Hi,
    this doent work for me, and i do not know why.
    the error whitch i get is:
    SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin ‘StringProperty [bean: TableRow[id=null, styleClass=cell indexed-cell table-row-cell], name: skinClassName, value: com.sun.javafx.scene.control.skin.TableRowSkin]’ for control TableRow[id=null, styleClass=cell indexed-cell table-row-cell]

    Can you help me pls?

  9. Hi,
    I have trouble to run it. I get “NullPointerException” and “Error on Building Data” when the column is added to the tableView.
    What can I do?

  10. “NullPointerException” and “Error on Building Data” – you get this when the database has null values.
    That works here:
    * Data added to ObservableList *
    ********************************/
    while(rs.next()){
    //Iterate Row
    ObservableList row = FXCollections.observableArrayList();
    for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
    //Iterate Column
    String str=null;
    if (rs.getString(i)==null){
    str = "";
    } else{
    str = rs.getString(i);
    }
    row.add(str);

  11. Hi,

    First, I want to thank you for the code. It “looks” so good… but… It won’t work for me.
    I use Netbeans IDE 8 with jdk 1.8.4.0 and JFX2.
    If I try to compile it, I get:
    =============================================
    Exception in thread “JavaFX Application Thread” java.lang.NullPointerException
    at dynamictable.DynamicTable$1.call(DynamicTable.java:55)
    at dynamictable.DynamicTable$1.call(DynamicTable.java:52)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
    +
    a lot of other lines…

    ==============================================
    ==============================================
    and my Netbeans warns me with a red bubble at this section:
    col.setCellValueFactory(
    new Callback<CellDataFeatures, ObservableValue>() {
    @Override
    public ObservableValue call(CellDataFeatures param) {
    return new SimpleStringProperty(param.getValue().get(j).toString());
    }
    }
    );
    =========================================
    ——————————————————–
    and the warning says:
    cannot find symbol:
    symbol constructor()

    cannot find symbol:
    symbol: class Callback

    ————————————————————

    Can you help me, please? (Could it be because I use Oracle, not MySQL? It fetches the ResultSet and everything, but… that error stops everything.

    Thank you!

  12. Hi guys

    I have created a netbeans project which shows the table of persons. My class which displays the TableView implements Initializable interface. On initiation, it takes up the data from the database (JavaDB). However, when I add some itmes to the underlying ObservableList, (I have different fxml file to create new person), I am not able to update the TableView. I have checked, my ObservableList gets updated but not the table. I tried with following code:

    tableViewData.add(person);
    tableView.getItems().add(person);

    None of these works. Can you help?

  13. Thank you very much.
    I have another problem.
    I have a database and the application of five TabPane in which they are TableView. How to display a data in table in one of the Tab?

  14. Hi, Your code is not working.
    On line 51
    return new SimpleStringProperty(param.getValue().get(j).toString());

    it does not recognize the get(j) method anymore
    do you have any other alternative.

  15. Thank you for this sample. It worked for me even long after you originally posted the information. However, it appears where you output the Row added to the console, you have a constant [1] in the position that should be a variable like rowCount. (Define before the while loop and increment after the for loop that adds the columns to the row). Thank you for your posting.

  16. If I have to display data from multiple tables how would I do it? For example I need to display manager, department, all employees reporting to the manager. How would I implement this?

  17. I tried to use this code with a TableView created using Scene Builder by declaring the TableView with @FXML. The code runs without any error and i can see the Rows in the console but the
    TableView has no content.

  18. Pingback: JavaFX Ref page | Chealwoo Web UI

  19. i am trying to get the colum name and data dynamically …..

    I am able to get the column dynamically but not data .
    It seems the data is coming but it is not displaying.

    Please find the code:

    int columnIndex = 0;
    TableColumn[] tableColumns = new TableColumn[derbyTableColumnNames.length];
    for (String columName : derbyTableColumnNames) {
    TableColumn col = new TableColumn(columName);
    tableColumns[columnIndex++] = col;
    }
    tableView.getColumns().clear();
    tableView.getColumns().addAll(tableColumns);

    ObservableList sourceDataList = FXCollections.observableArrayList();
    for (String[] columnData : derbyTableColumnData) {
    //tableView.setItems(Arrays.asList(columnData));
    ObservableList row = FXCollections.observableArrayList();
    for (String rowData : columnData) {
    System.out.println(“\t” + rowData);
    row.add(rowData);
    }

    sourceDataList.add(row);
    }
    tableView.setItems(sourceDataList);

    Please let me know the problen as soon as possible.

  20. Thank you very much for your effort.
    I got your code work fine with MySQL DB. When I tried to run it with Oracle I got the same error as Dinu Ionut above.
    My Apology for the long error message.
    Would you please help.

    Thanks

    Exception in thread “JavaFX Application Thread” java.lang.NullPointerException
    at tableview.DynamicTable$1.call(DynamicTable.java:55)
    at tableview.DynamicTable$1.call(DynamicTable.java:53)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
    at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
    at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
    at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
    at com.sun.javafx.scene.control.skin.TableViewSkin.resizeColumnToFitContent(TableViewSkin.java:241)
    at com.sun.javafx.scene.control.skin.TableViewSkin.resizeColumnToFitContent(TableViewSkin.java:54)
    at com.sun.javafx.scene.control.skin.TableColumnHeader.doColumnAutoSize(TableColumnHeader.java:531)
    at com.sun.javafx.scene.control.skin.TableColumnHeader.updateScene(TableColumnHeader.java:474)
    at com.sun.javafx.scene.control.skin.TableColumnHeader.handlePropertyChanged(TableColumnHeader.java:314)
    at com.sun.javafx.scene.control.skin.TableColumnHeader.lambda$new$49(TableColumnHeader.java:149)
    at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(MultiplePropertyChangeListenerHandler.java:55)
    at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
    at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
    at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
    at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
    at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
    at javafx.scene.Node$ReadOnlyObjectWrapperManualFire.fireSuperValueChangedEvent(Node.java:831)
    at javafx.scene.Node.invalidatedScenes(Node.java:881)
    at javafx.scene.Node.setScenes(Node.java:919)
    at javafx.scene.Parent$1.onChanged(Parent.java:269)
    at com.sun.javafx.collections.TrackableObservableList.lambda$new$19(TrackableObservableList.java:45)
    at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
    at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
    at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
    at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
    at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
    at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
    at javafx.collections.ModifiableObservableListBase.setAll(ModifiableObservableListBase.java:90)
    at com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:116)
    at com.sun.javafx.scene.control.skin.NestedTableColumnHeader.updateContent(NestedTableColumnHeader.java:487)
    at com.sun.javafx.scene.control.skin.NestedTableColumnHeader.updateTableColumnHeaders(NestedTableColumnHeader.java:317)
    at com.sun.javafx.scene.control.skin.NestedTableColumnHeader.checkState(NestedTableColumnHeader.java:544)
    at com.sun.javafx.scene.control.skin.NestedTableColumnHeader.computePrefHeight(NestedTableColumnHeader.java:427)
    at javafx.scene.Parent.prefHeight(Parent.java:929)
    at javafx.scene.layout.Region.prefHeight(Region.java:1435)
    at com.sun.javafx.scene.control.skin.TableHeaderRow.computePrefHeight(TableHeaderRow.java:331)
    at com.sun.javafx.scene.control.skin.TableHeaderRow.computeMinHeight(TableHeaderRow.java:324)
    at javafx.scene.Parent.minHeight(Parent.java:957)
    at javafx.scene.layout.Region.minHeight(Region.java:1401)
    at javafx.scene.control.SkinBase.computeMinHeight(SkinBase.java:254)
    at javafx.scene.control.Control.computeMinHeight(Control.java:487)
    at javafx.scene.Parent.minHeight(Parent.java:957)
    at javafx.scene.layout.Region.minHeight(Region.java:1401)
    at javafx.scene.Scene.getPreferredHeight(Scene.java:1710)
    at javafx.scene.Scene.resizeRootToPreferredSize(Scene.java:1674)
    at javafx.scene.Scene.preferredSize(Scene.java:1645)
    at javafx.scene.Scene.impl_preferredSize(Scene.java:1720)
    at javafx.stage.Window$9.invalidated(Window.java:846)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at javafx.stage.Window.setShowing(Window.java:922)
    at javafx.stage.Window.show(Window.java:937)
    at javafx.stage.Stage.show(Stage.java:259)
    at tableview.DynamicTable.start(DynamicTable.java:97)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
    Exception in Application start method
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
    Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.NullPointerException
    at tableview.DynamicTable$1.call(DynamicTable.java:55)
    at tableview.DynamicTable$1.call(DynamicTable.java:53)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
    at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
    at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
    at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
    at com.sun.javafx.scene.control.skin.TableRowSkin.(TableRowSkin.java:64)
    at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
    at javafx.scene.control.Control.impl_processCSS(Control.java:859)
    at javafx.scene.Node.processCSS(Node.java:9056)
    at javafx.scene.Node.applyCss(Node.java:9153)
    at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1964)
    at com.sun.javafx.scene.control.skin.VirtualFlow.addTrailingCells(VirtualFlow.java:1344)
    at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1197)
    at javafx.scene.Parent.layout(Parent.java:1087)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Scene.doLayoutPass(Scene.java:552)
    at javafx.scene.Scene.preferredSize(Scene.java:1646)
    at javafx.scene.Scene.impl_preferredSize(Scene.java:1720)
    at javafx.stage.Window$9.invalidated(Window.java:846)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at javafx.stage.Window.setShowing(Window.java:922)
    at javafx.stage.Window.show(Window.java:937)
    at javafx.stage.Stage.show(Stage.java:259)
    at tableview.DynamicTable.start(DynamicTable.java:97)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)

  21. Thank you very much for your effort.
    I got your code work fine with MySQL DB. When I tried to run it with Oracle I got the same error as Dinu Ionut above.
    This is a short error message.

    Would you please help.

    Thanks
    java.lang.NullPointerException
    Error on Building Data
    at tableview.DynamicTable.buildData(DynamicTable.java:44)
    at tableview.DynamicTable.start(DynamicTable.java:92)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)

  22. Hello, is there any way to pass the the data in my existing TableView in another window which i builded using FXML, without the need of pop-up a window like this code does?

  23. Add this:
    if (param.getValue().get(j) != null) {
    return new SimpleStringProperty(param.getValue().get(j).toString());
    } else {
    return new SimpleStringProperty();
    }
    to the Table Colum Added Dynamically routine. Then the App doesn’t crash if the cell is empty

  24. thanks alot my friend ;
    but how can I make the table view refreshable after entring new records ..
    I tried to call the method inside the action event of adding button but it dupplicates the table view and not get the new records
    so I have to restart run the program again to load the data
    thanks

  25. Once you have the data in the tableview, how can you process it (i.e. for each row, have the data sent to another process)?

  26. hey thanks for this greet code. but i have a question what if i want to add button i each row automatically generated. how to do that?

  27. Hi
    Since I last viewed this useful example, which I am using in my project, the code window seems to have scrampled and now contains the raw HTML code. I don’t know if this is because of the platform that displays the code, because some change has been made to the content that has inadvertently scrambled the code, or because of my (Firefox 56.0.2) browser. The code itself can be retrieved from the ‘open code in a new window’ marker at the top right of the scrambled window.

Leave a Reply