【问题标题】:JTable, refreshing rowData vector in static contextJTable,在静态上下文中刷新 rowData 向量
【发布时间】:2013-07-18 12:52:12
【问题描述】:

我已经声明了一个 JTable(在类扩展的 JPanel 构造函数中),例如

data_table = new JTable(info, header) {
    @Override
    public boolean isCellEditable(int row, int column) {
        //disable table editing
        return false;
    }
};

声明信息和列的位置

static String[][] info = new String[row][cols];
static String[] header = {"h1", "h2", "h3"};

现在我需要在某些事件发生时通过调用静态方法来更新表格内容。我该怎么做?

【问题讨论】:

    标签: java swing jtable


    【解决方案1】:

    我没有 tableModel,我有一个字符串矩阵

    所有表都使用 TableModel。创建表格时,TableModel 使用字符串矩阵。

    要更新您的数据,您可以执行以下操作:

    table.setValueAt(...);
    

    这将导致模型被更新,并且模型会告诉表格重新绘制自己。

    阅读How to Use Tables 上的 Swing 教程,了解有关表格的更多信息。

    另外,您不应该使用静态变量或方法。如果你是,那么你的程序设计得很糟糕。再次阅读教程,了解如何构建代码的更好示例。

    【讨论】:

    • 对不起,我没有很好地解释我的问题。我不需要修改广告现有数据行,但我需要将一些新行“追加”到 JTable。
    • 使用DefaultTableModel的addRow(...)方法。
    【解决方案2】:

    如果您想通知您的 JTable 您的数据更改,请在您的 tablemodel 上调用一个方法来更新数据并调用 fireTableDataChanged()

    使用 JTableModel 在 JTable 中维护数据是一种很好的做法。 http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

    这就是你的表格模型,当值发生变化时会触发fireTableDataChanged()。

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = ...//same as before...
        private Object[][] data = ...//same as before...
    
        public int getColumnCount() {
            return columnNames.length;
        }
    
        public int getRowCount() {
            return data.length;
        }
    
        public String getColumnName(int col) {
            return columnNames[col];
        }
    
        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
    
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    
        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 2) {
                return false;
            } else {
                return true;
            }
        }
    
        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
        ...
    }
    

    【讨论】:

    • -1,你不应该直接使用 tableModel.fireXXX 方法。 fireXXX 方法只能由 TableModel 本身调用。
    • 我没有tableModel,我有一个字符串矩阵。
    • @giozh 你必须有一个tableModel,这是正确设置带有数据的JTable的唯一方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2015-09-06
    • 2011-12-05
    • 2014-12-25
    相关资源
    最近更新 更多