简体   繁体   中英

Format data from JDBC in JTable with complex TableCellRenderer

I'm trying to implement a simple discussion board in Java and have run into some problems with displaying data via JDBC in my JTable .

I have created a working prototype of how I want it to look in the end

I have connected to my PostgreSQL database via JDBC

What are some best practices here? Should I work with vectors, TableModel ? I can't seem to find any good sample code for this.

Most importantly: How can I display the contents of two columns of my database in on JTable field?

You almost always want to write your own subclass of AbstractTableModel. At a minimum, you will need to write getRowCount , getColumnCount , and getValueAt methods for it. Typically, a table model returns data based on a private List (such as private List<BoardMessage> messages ).

The advantage of writing your own model is that the types of each column are a lot easier to keep track of, and there is far less room for error. You can give your model class additional methods like public void addMessage(BoardMessage message) and the model can take care of returning the appropriate values in its getValueAt method. This is much cleaner and less prone to error than just trying to add things to a bare Vector of Vectors.

Your model class also acts as, well, a data model, in that you can add a method like public BoardMessage getMessageAt(int row) , which is useful when a user performs an action on a particular message.

It's not a good practice to perform JDBC calls inside a table model, because they take time to execute and that will hold up the AWT event dispatch thread, which causes the user interface to become unresponsive. The better thing to do is to execute a JDBC select call in a different Thread, create data objects (such as a List of BoardMessage instances) from the ResultSet, then use EventQueue.invokeLater to update your model with the new data objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM