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.
Hi,
Thank you for reminding the bug. I have just fixed that issue 🙂 .
Thanks
ObservableList cannot be converted to ObservableList
hello,
I am getting this error it can not be string why?
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
It works awsm… thanks
The below part of code never works for me, I am not getting any values in TableView for rows. I am getting only column names inside the table.
while(rs.next()){
ObservableList row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
row.add(rs.getString(i));
}
System.out.println(row );
data.add(row);
}
//FINALLY ADDED TO TableView
tableview.setItems(data);
Hi Meena,
Do you have any data in that tables ?
If you need to get start with this you can clone : https://github.com/privatejava/javafx-dynamic-tableview
Thanks
Is it working in inner join ?
Yes you can
Thanks Bro. You saved my Project from being a trash
hi
im not able to see data on the tableView but data got added to observable list
Thanks for sharing this information
do you have video tutorial?
Nice code !!!!! You helped me so much for my exam. theres only one little unimported mistake or not solved, come on…..doesnt matter…
nice nice nice