[英]How to refresh a JTable without setting a new table model?
I am trying to refresh a JTable
using the DefaultTableModel
without accessing the table itself again, but only the existing, but then updated table model. 我试图使用
DefaultTableModel
刷新JTable
,而不再次访问表本身,但仅访问现有表,然后再更新表模型。
Yet, I tried to update the table model itself and then notify the model about it (see in the code). 但是,我尝试更新表模型本身,然后将其通知模型(请参见代码)。 For some reason, the table will not update.
由于某种原因,该表将不会更新。 I do not know, if this is an access problem or if it is just not possible.
我不知道这是访问问题还是无法实现。
//in the Gui_Main class
private static void addTables(){
JTable tblMain = new JTable(Util_Tables.dtm);
}
//in the Util_Tables class, if the tables needs to be updated
public static DefaultTableModel dtm;
public static void updateTable(){
dtm = new DefaultTableModel(data, columns);
dtm.fireTableDataChanged();
}
So you're basic structure is all over the place. 所以您的基本结构无处不在。 When you create a new instance of
DefaultTableModel
and assign it to dtm
, this won't be reflected by the JTable
, as it is still using the instance it first grabbed when it was created. 当创建
DefaultTableModel
的新实例并将其分配给dtm
, JTable
不会反映出来,因为JTable
仍在使用创建时首先抓取的实例。
Exposing dtm
the way you have, opens it up to undesirable modification and voids one of the principles of OO - encapsulation, where the class is responsible for the management of its properties. 公开
dtm
的方式,将其开放给不良的修改,并使OO的原理之一-封装(encapsulation),其中类负责其属性的管理。 This is also a reason to reconsider the use of static
这也是重新考虑使用
static
的原因
A better start would be to create a getter which returns a single instance of DefaultTableModel
, so each call to it is guaranteed to return the same instance of DefaultTableModel
and stops any one else from changing the underlying reference 更好的开始是创建一个getter,该方法返回一个
DefaultTableModel
实例,因此对它的每次调用都可以保证返回相同的DefaultTableModel
实例,并阻止其他任何实例更改基础引用
private static void addTables(){
JTable tblMain = new JTable(Util_Tables.getModel());
}
//in the Util_Tables class, if the tables needs to be updated
private DefaultTableModel model;
public static DefaultTableModel getModel() {
if (model == null) {
model = new DefaultTableModel();
}
}
Okay, so how about updating the model? 好的,那么更新模型呢? Well, you need to start by modifying your
updateTable
method, so it can be used to actually update the model in some meaningful way 好吧,您需要从修改
updateTable
方法开始,以便可以使用它以某种有意义的方式实际更新模型
public static void updateTable(Object[][] data, Object[] columnIdentifiers){
model.setDataVector(data, columnIdentifiers);
}
The model will then generate the events it needs itself. 然后,该模型将生成自己需要的事件。 If you find yourself calling the
fireXxx
methods yourself, then it's a good indication that you're doing something wrong. 如果您发现自己在调用
fireXxx
方法,则表明您做错了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.