In my JTable, I want to rename the table header using right click option.on Right clicking on any header it gives option for rename header.but when I am doing this it will do rename of selected column's header. So I have to first left click on that column then I can further processed. Is there any way that when I am Right click on any column,it also get selected so that after rename it's value is got renamed.
My action listener is as below :
int column = jTable1.getSelectedColumn();
if (column == -1) {
return;
}
if (column == 0) {
JOptionPane.showMessageDialog(jTable1, "You can not rename this column.");
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;
}
Vector vColumns = new Vector();
for (int i = 0; i < defaultTableModel.getColumnCount(); i++) {
vColumns.add(defaultTableModel.getColumnName(i));
}
if (vColumns.contains(sColumnName)) {
JOptionPane.showMessageDialog(jTable1, "Column name " + sColumnName + " already exist.");
return;
}
}
int viewColumn = jTable1.convertColumnIndexToView(column);
int totalColumn = defaultTableModel.getColumnCount();
Object[] headers = new Object[totalColumn];
for (int i = 0; i < totalColumn; i++) {
if (i == column) {
headers[i] = sColumnName;
} else {
headers[i] = defaultTableModel.getColumnName(i);
}
}
defaultTableModel.setColumnIdentifiers(headers);
I miss there
1)
MouseListener
and determine selectedColumn
with value retuns2) code for change
header.getColumnModel().getColumn(i).setHeaderValue("Clicked");
simple example
3) another way is add CellEditor to the JTableHeader (notice never tried, and not sure if editor works as expects, only example, I'm sure that required a few modifications)