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.
1 2 3 4 5 6 7 8 |
Customer Table +----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | col0 | int(11) | NO | PRI | NULL | auto_increment | | col1 | varchar(200) | NO | | NULL | | | col2 | int(4) | NO | | NULL | | +----------------+--------------+------+-----+---------+----------------+ |
JavaFX 2.0 SourceCode
Main GUIClass
This class consists all the GUI Components and the data are being extracted from database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import java.sql.Connection; import java.sql.ResultSet; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.stage.Stage; import javafx.stage.WindowEvent; import javafx.util.Callback; /** * * @author Narayan */ public class DynamicTable extends Application { //TABLE VIEW AND DATA private ObservableList<ObservableList> data; private TableView tableview; //MAIN EXECUTOR public static void main(String[] args) { launch(args); } //CONNECTION DATABASE public void buildData() { Connection c; data = FXCollections.observableArrayList(); try { c = DBConnect.connect(); //SQL FOR SELECTING ALL OF CUSTOMER String SQL = "SELECT * from CUSTOMER"; //ResultSet ResultSet rs = c.createStatement().executeQuery(SQL); /** * ******************************** * TABLE COLUMN ADDED DYNAMICALLY * ********************************* */ for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { //We are using non property style for making dynamic table final int j = i; TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i + 1)); col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() { public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) { return new SimpleStringProperty(param.getValue().get(j).toString()); } }); tableview.getColumns().addAll(col); System.out.println("Column [" + i + "] "); } /** * ****************************** * Data added to ObservableList * ******************************* */ while (rs.next()) { //Iterate Row ObservableList<String> row = FXCollections.observableArrayList(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { //Iterate Column row.add(rs.getString(i)); } System.out.println("Row [1] added " + row); data.add(row); } //FINALLY ADDED TO TableView tableview.setItems(data); } catch (Exception e) { e.printStackTrace(); System.out.println("Error on Building Data"); } } @Override public void start(Stage stage) throws Exception { //TableView tableview = new TableView(); buildData(); //Main Scene Scene scene = new Scene(tableview); stage.setScene(scene); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { Platform.exit(); System.exit(0); } }); stage.show(); } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author Narayan */ public class DBConnect { private static Connection conn; private static String url = "jdbc:mysql://localhost/test"; private static String user = "root"; private static String pass = "rootp@$$"; public static Connection connect() throws SQLException{ try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); }catch(ClassNotFoundException cnfe){ System.err.println("Error: "+cnfe.getMessage()); }catch(InstantiationException ie){ System.err.println("Error: "+ie.getMessage()); }catch(IllegalAccessException iae){ System.err.println("Error: "+iae.getMessage()); } conn = DriverManager.getConnection(url,user,pass); return conn; } public static Connection getConnection() throws SQLException, ClassNotFoundException{ if(conn !=null && !conn.isClosed()) return conn; connect(); return conn; } } |
In above class the url,user,pass may varies according to your mysql configuration.
Output:
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.
Dear friend, I feel the need to communicate that I have tested your code and agradesco but I encountered the following error, I would appreciate complete or provide the code to tell me I’m doing wrong, thanks.
SEVERE: javafx.scene.control.Control loadSkinClass Failed to load skin ‘com.sun.javafx.scene.control.skin.TableRowSkin’ for control TableRow@d4d66b[styleClass=table-row-cell]
java.lang.IllegalStateException: Cannot read from unreadable property 0
I am of Mexican nationality and thanks for sharing knowledge.
my email is: [email protected]
Thanks for sharing this wonder full blog Dynamic TableView Data From Database.It is very useful for me.
Hello, I’m from Brazil, I’m having problems with ClassNotFoundException’ve tried postgres and mysql and the two are into the same error can you help me?
but it runs very well actually! Have you kept mysql driver in library project?
Thanks.
Greetings from Philippines!
Hello Sir. This is a wonderful tutorial.
I am looking for a tableview sample that will display image in a column. I hope you can share your knowledge sir, if you have an idea.
Thank you in advance.
Hello,
try to write instead this:
int i = Integer.parseInt(col.getProperty());
this:
int i = Integer.parseInt(col.getProperty())-1;
thnx man
Nice but no includes in code … I guess because API is unstable
BTW CellDataFeatures has disappeared from latest FX build, 42
keep the nice work
regards
patrick http://www.zion-dba.com
Hi Sir
can you help to figure out this error “can not find symbol” when define the “private TableView tableview;”
in your DynamicTable.java below
Mine is using JavaFX 2.0 SDK to compile. Please forgive me if any inconvenience since I’m a newbie in this FX technology
Thanks
The issue of cannot find symbol “TableView” has been resolved by import the javafx.scense.control.TableView , however i faced one issue with the “object” in ObservableList row = FXCollections.observableArrayList(); It got error when compiled, It says: “error: cannot find symbol”
Can you please help to tell me why it is?
Thanks
You need to import ObservableList,FXCollections . To know more about classes. Please see the JavaFX Documentation : http://download.oracle.com/javafx/2.0/api/index.html
Hi Sir
I’m sorry to come back again,
Actually i do import the two FXCollection & ObservableList in two command (import javafx.collections.FXCollections;
import javafx.collections.ObservableList;)
but the “object” issue still there.
my JavaFX 2.0 SDK is 64 bits on windows 7
Is that the place issue coming from?
Can you please explain the and it usage in the code ?
the error when compiled : (Compiling 1 source file to C:\Projects\DynamicTable\build\classes
C:\Projects\DynamicTable\src\DynamicTable.java:69: cannot find symbol
symbol : class object
location: class DynamicTable
ObservableList row = FXCollections.observableArrayList();
Note: C:\Projects\DynamicTable\src\DynamicTable.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error)
Thank you very much
Re-edit “Can you please explain the and it usage in the code ?” = “Can you please explain the usage of in the line code ?”
Thank you
Re-edit “Can you please explain the and it usage in the code ?” = “Can you please explain the usage of the “object” in the line code ?”
Thank you
Hi Le Hong,
Sorry for the inconvenience you have got. I’ve edited the code. Now the code will works fine. The Object was used for taking any kind of value. All the class in java are extended from class ‘Object’.
Thank you very much for your reply
i get confused with “object” instead of “Object” ::))
I think this example is much applicable into real life and best suit for the one that just step into this Java industry like me.
One more thing that i would like to ask for a favor
Could you please write a example code to call a window from a window (in JavaFX), eg we can call the PiechartDemo from DynamicTableView with a button or a hyperlink inside the current DynamicTableView :))
Sorry if i asked a very basic question
Thanks and regards
The ‘Object’ is the base Class of Java. you can see its documentation on javadoc http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html.
And the way to call the window from window is to use Popup Class which is quiet easier like Stage. You can see the javafx doc of Popup at here : http://download.oracle.com/javafx/2.0/api/index.html?javafx/stage/PopupWindow.html
Not sure if the TableColumn class has changed but it has no setDataRetriever method.
The API page for TableColumn has an example that uses setCellValueFactory but I can’t see how it can be used in the same way that not knowing the data type on the ResultSet.
If someone knows how to do can they please explain how to do it.
Regards
Munga
This code does not compile in the current JavaFX api, TableColumn does not have methods setProperty, setDataRetriever & getProperty.
41 col.setProperty(String.valueOf(i));
42 col.setDataRetriever(new Callback<CellDataFeatures,Object>(){
43 public String call(CellDataFeatures param) {
44 int i = Integer.parseInt(col.getProperty());
Does anyone know how to get around this issue?
Thanks
Munga
Pingback: set up your own minecraft sever today
Great Blog and writing…. very helpful for JavaFX beginner in data source……… thank you so much Mr.Narayan…. this blog is so awesome… 🙂
You are welcome !
Dear Narayan!
when i run the pie chart application in netbeans ide , “Error in DB ” ocurrs,
Pls mail me the complete code for this application.
i will be very grateful to you for this kindness
hi
are you sure you have correct database and correct tables for this dynamic table view?
Sir,
pls mail me complete code of Dynamic Table View in netBeans ide project form as a zip. file.
Regards
Dear Narayan,
The examples on your blog are some of the most clear and well explained that I have found. I’m involved with a JavaFX application that creates dynamic crosstabs from framework files that provide the layout. Separate data files then populate the cells. I’m able to create tables with grouped headings and I’ve been able to populate them by following your example. I now have a requirement to provide checkboxes (sometimes with or sometimes without text) in all the table columns except the first and to get back the row/column references of the check boxes. I also need to make the checking of the first box in a column cause all the boxes in that column to be checked, and similarly for the first box in a row and all boxes in that row. I would be very grateful to see some sample code for any TableView/CheckBox application if you happen to have it. Best wishes.
Hellow Dmv,
For the event of checkbox you can directly fire the event and make changes on the ‘items’ of the TableView then the TableView itself get’s updated because the ‘items’ of TableView are inherited from the ObservableList which is actually bindable to the GUI of TableView.
Thanks
Narayan
Thank you, Narayan, for a helpful reply but it is the details of implemention that are my problem. I will continue to experiment using your Music sample as a basis and adding another column.
A beautiful day.Very good blog! Very good. striking. I will bookmark your site, feed addition … I am very pleased to find so much useful information here. Thank you to share …
Very useful comments, never heard it before.thank you to share such good information. I have bookmark this blog and share with my friend. I hope a good day.lol
Thank you very much for this great example!
i’ve tried this codes… and it works fine…
except, if i put the tableview into a ScrollPane, the header also moving when i’m scrolling data vertically, i mean, the header didn’t stay in that position..
i used this codes :
ScrollPane scrollpane1 = new ScrollPane(); scrollpane1.setContent(tableview);
is it any way to make the first row (Header) staying in that position when i’m scrolling vertically???
any help will be really appreciated..
Hi Linda Fitriani,
TableView already have the Scrollpane in itself You don’t need to add the ScrollPane explicitly.
Thanks
Narayan
@ Mr, Narayan,
it’s really helpful, thank you… 🙂 actually, i’m trying to make a row header too
is it any way to make a row header ? the first row that not move when i scrolled horizontally, but it’s move when i scrolled vertically…
Hello Linda, As far as I know, there is not yet any specific provision for row headers. I use them in my tables but there are just another column.
Hi Linda,
I guess there is no any thing like that currently possible in JavaFX. But somehow in new JavaFX there is customization in Table Header. May be those can be useful
Thanks
Narayan
@ Mr. Dmv and Mr. Narayan.. thank u for that helpful info.. 🙂
How can we do to add a datascroller with fixed number of line fot a tableview?
Like rich:dataTable and rich:dataScroller on richfaces.
regards
I’m afraid, But i didn’t understand what you are trying to tell 🙁
Sorry, the javafx tableview display all List of value that you give to him, if the list contain 1 000 lines the system display all the lines.
I want to fix the number of line visible at 20 for example, and add scroll between pages with buttons:
______________
!COL1 !COL2 !
______________
!row1 !row1 !
!row2 !row2 !
………………….
!row20!row20!
______________
<< >> to move betweens pages.
Of course I want to keep he sort functionality.
On JSF this system is implemented by RichFaces or IceFace for example, I try to found on the web the same system without success.
Hi sebastien,
Ok so you want to do pagination in tableview. To make this pagination you need to make your own control or you can add some butons to control over the tableview items. Save the whole thousands of items in ObservableList and do setItems() of the TableView according to the button clicked.
For eg. There are thousand of records in ObservableList->datas
Now make two buttons for instance Button(“< "), Button(">“) .
If you you clicked on Button “>” then update the table view with the datas you need to show up using setItems().
Thanks,
I agree with you, but you have also to implement your own sort column too, the default is applied only on the list that you assign via the setitem not on all list.
I do not understand why this functionality is not included with the tables in java.
thanks
Ya sebastien,
You are right we need to add our own sort because the Tableview only updates the one which is available in it’s items.
I found this information:
https://forums.oracle.com/forums/thread.jspa?threadID=2273405
may be on future version it will be implemented.
If i get time then May be i’ll be making one custom control of TableView having Pagination 🙂
Thanks
Hi
small question regarding tableview
if tv data has changed ( JPA , whatever … ) how is one to
update( refresh ) it ?
Hi baikelin,
All the tableview data are directly related to the ObservableList items . So if there is any update occured in the database or JPA then you must update the ObservableList items of tableview.
value)Thanks
when i run this code i am getting null pointer exception at
tableview.getColumns().addAll(col); this line can anyone help me