Wednesday, April 21, 2010

Selecting columns or rows but not cells in JTable

Here is a snippet to enable selection of either columns or rows, but not cells, in a JTable:
   public Integer findColumn(JTable table, Point p)
{
JTableHeader tableHeader = table.getTableHeader();
p.translate(-tableHeader.getX(), -tableHeader.getY());
if(p.x >= 0 && p.x < tableHeader.getSize().width &&
p.y >= 0 && p.y < tableHeader.getSize().height)
{
int x = p.x;
for(int i = 0; i < table.getColumnCount(); i++)
{
String columnName = table.getColumnName(i);
TableColumn column = table.getColumn(columnName);
x -= column.getWidth();
if(x < 0)
{
return column.getModelIndex();
}
}
}

return null;
}

public void enableRowSelection(final JTable table)
{
table.getTableHeader().addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
table.getSelectionModel().clearSelection();
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
int column = findColumn(table, e.getPoint());
table.getColumnModel().getSelectionModel().
setSelectionInterval(column, column);
}
});
table.addMouseListener(new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
table.getColumnModel().getSelectionModel().
clearSelection();
}
});
}

Some adjustment may be needed to enable selection of single/multiple columns or rows.