How can I sync default table model with table header?
I have written action listener on column header that allowing user to rename the selected column and add a new column.
Code to rename the column -
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);
开发者_C百科 tableColumn.setHeaderValue(sColumnName);
jTable1.getTableHeader().repaint();
Code to add new column in 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);
But the issue is when I rename the column and then add a new column, a new column is getting added but it show the old name of just renamed column.
How can I sync default table model with table header ?
There's no API for renaming headers on the Default/TableModel. The options are to either subclass/implement a custom model or trick the default, something like this (pseudo-code):
Object[] headers = new Object[tableModel.getColumnCount()];
forEach (model-column)
if (index == renamedColumn)
headers[index] = newHeader
else
headers[index] = tableModel.getColumnName(index)
tableModel.setColumnIdentifiers(headers)
(Note: assumes identifier is same as name)
精彩评论