简体   繁体   English

使用复杂的TableCellRenderer格式化JTable中JDBC的数据

[英]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 . 我正在尝试用Java实现一个简单的讨论板,并且在我的JTable通过JDBC显示数据遇到了一些问题。

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 我通过JDBC连接到我的PostgreSQL数据库

What are some best practices here? 这里有哪些最佳做法? Should I work with vectors, TableModel ? 我应该使用向量, 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? 最重要的是:如何在JTable字段中显示我的数据库的两列内容?

You almost always want to write your own subclass of AbstractTableModel. 您几乎总是想编写自己的AbstractTableModel子类。 At a minimum, you will need to write getRowCount , getColumnCount , and getValueAt methods for it. 至少,您需要为它编写getRowCountgetColumnCountgetValueAt方法。 Typically, a table model returns data based on a private List (such as private List<BoardMessage> messages ). 通常,表模型基于私有列表(例如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. 您可以为模型类提供其他方法,例如public void addMessage(BoardMessage message) ,并且模型可以负责在其getValueAt方法中返回适当的值。 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. 您的模型类也可以充当数据模型,因为您可以添加public BoardMessage getMessageAt(int row) ,这在用户对特定消息执行操作时很有用。

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. 在表模型中执行JDBC调用并不是一个好习惯,因为它们需要时间来执行并且会占用AWT事件调度线程,这会导致用户界面无响应。 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. 更好的做法是在不同的Thread中执行JDBC select调用,从ResultSet创建数据对象(例如BoardMessage实例的List),然后使用EventQueue.invokeLater用新的数据对象更新模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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