JavaFX 2.0 TableView in FXML with Data from Databa

2019-02-21 02:25发布

I am wondering how can I retrieve data from a mysql database into a tableview which is into a fxml file. I must retrieve the data and place it into a tableview which is located in a fxml file. I have the idea of how I will connect to the database, but I don't know how to retrieve the data and place it into tableview.

The tableview is in a fxml file. If I am still here, anyone know after I import the data how can I edit the cells in this tableview?

The application I work on is a desktop one!

2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-21 02:45

AFAIK, you cannot retrieve and display the data from DB in FXML file, and make the tableview cells editable in FXML file. Even though it was possible (maybe partially through custom Builder and BuilderFactory), it is not recommended to do that in a sense of MVC. Please read about Why Use FXML and its benefits first. Still you can define some basic data structures in FXML file if it is so necessary, see Introduction to FXML.
So do your non-view related tasks in a initialize() method of the controller, namely retrieve data and set the items of the tableview. Customize the cell factories of the table columns to support editing and so on.

查看更多
爷的心禁止访问
3楼-- · 2019-02-21 02:57

There are a few ways to do this, one is to use the JDBC adapter from DataFX.

Update

FXML itself just defines an xml based UI structure, it cannot load data from a database.

When the data originates from the database, creating a static fxml file containing the data values is likely a bad idea in most cases. Anytime the data in the database changes, you will need to generate and load a new fxml file and for that you will need to either create the new file by hand or write a fragile program to generate the new fxml file based upon the data in the database.

Suggested approach:

  1. Use the fxml only to define your TableView structure but not to contain actual data values.
  2. In your JavaFX Java code connect to the mysql database.
  3. Use the DataFX JDBC data source adapter to retrieve the data from the database and populate your TableView.

You could write your own code to do step 3. Using your own code might be a good idea if you wish to use JPA (which I think DataFX does not currently directly support). Otherwise you will probably end up with better results quicker using the DataFX implementation.

To find out how to do edits in TableView, read this TableView tutorial. Again, DataFX will help you by providing Control Cell Factories for edits - so I'd recommend using DataFX for this rather than handcoding the TableView edit handling.

I'm not sure if the DataFX code will help you when you need to commit edits to a database; in that case you will probably need to add your own JDBC or JPA code to commit the changes.

查看更多
登录 后发表回答