如何将默认表模型与表头同步?

时间:2011-04-22 09:31:19

标签: java swing

我在列标题上编写了动作侦听器,允许用户重命名所选列并添加新列。

重命名列的代码 -

int column = jTable1.getSelectedColumn();

            if (column == -1) {
                return;
            }
            boolean blag = true;
            String sColumnName = null;
            while (blag) {

                sColumnName = (String) JOptionPane.showInputDialog(jTable1, "Enter Column Name", "Add Column", JOptionPane.INFORMATION_MESSAGE, null, null, null);

                if (sColumnName == null) {
                    return;
                }
                if (sColumnName.trim().equalsIgnoreCase("")) {
                    JOptionPane.showMessageDialog(jTable1, "Column name can not be blank.");
                    blag = true;
                } else {
                    blag = false;
                }

            }
            int viewColumn = jTable1.convertColumnIndexToView(column);
            TableColumn tableColumn = jTable1.getColumnModel().getColumn(viewColumn);
            tableColumn.setHeaderValue(sColumnName);
            jTable1.getTableHeader().repaint();

在JTable中添加新列的代码。

boolean blag = true;
            String sColumnName = null;
            while (blag) {

                sColumnName = (String) JOptionPane.showInputDialog(jTable1, "Enter Column Name", "Add Column", JOptionPane.INFORMATION_MESSAGE, null, null, null);

                if (sColumnName == null) {
                    return;
                }
                if (sColumnName.trim().equalsIgnoreCase("")) {
                    JOptionPane.showMessageDialog(jTable1, "Column name can not be blank.");
                    blag = true;
                } else {
                    blag = false;
                }

            }

            defaultTableModel.addColumn(sColumnName);

但问题是当我重命名列然后添加新列时,会添加一个新列,但它会显示刚重命名的列的旧名称。

如何将默认表格模型与表格标题同步?

1 个答案:

答案 0 :(得分:3)

在Default / TableModel上没有重命名标头的API。选项是子类/实现自定义模型或欺骗默认值,如下所示(伪代码):

Object[] headers = new Object[tableModel.getColumnCount()]; 
forEach (model-column)
    if (index == renamedColumn)
       headers[index] = newHeader
    else
       headers[index] = tableModel.getColumnName(index)
tableModel.setColumnIdentifiers(headers)

(注意:假定标识符与名称相同)