本文介绍了JTable不更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,调用此JTable时没有任何变化(此方法在用户提交SQL查询后更新JTable)。

For some reason, nothing changes about this JTable when this is called (this method updates the JTable after a user submits an SQL query).

Givens:
验证dataVector和columnNamesVector是否正确填充。
JTable是一个私有类变量。

Givens:The dataVector and columnNamesVector are verified to be populated correctly.JTable is a private class variable.

private void updateData() {
    updateDataVariables();
    table = new JTable(dataVector, columnNamesVector)
    {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }
            }

            return Object.class;
        }
    };
}

任何想法?

推荐答案

将对象与引用变量混淆是一个常见的初学者谬论,但你需要明白它们是截然不同的。当你这样称呼时:

It's a common beginner's fallacy to confuse objects with reference variables, but you need to understand that they are quite distinct. When you call this:

table = new JTable(dataVector, columnNamesVector) {.....

您正在创建一个新的JTable对象并让表变量引用它,但这对JTable没有影响GUI显示的 object ,表变量之前引用的那个。所以你要改变引用变量的属性,但保持原始对象不变。

You are creating a new JTable object and having the table variable refer to it, but this has no effect on the JTable object that is displayed by the GUI, the one that the table variable was referring to previously. So you're changing the property of the reference variable, but leaving the original object unchanged.

解决方案:你不应该创建一个新的JTable,而应该是创建一个新的TableModel,然后将该TableModel放入现有的可视化JTable中。您可以通过调用 setModel(newModel)来更改表的模型。

The solution: You should not be creating a new JTable but rather you should be creating a new TableModel and then place that TableModel into the existing and visualized JTable. You can change a table's model by calling setModel(newModel) on it.

编辑:或者像wolfcastle注意到的那样可以更新现有的TableModel而不是重新创建一个。

or as wolfcastle noted you could update the existing TableModel rather than create one anew.

这篇关于JTable不更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:52