How to make a column header immovable in JTable

I am not fulltime Swing developer but I have come to this little problem quite lately.  JTable columns headers are movable by default which sometimes can be annoying. Even if you do not want to move them you can do it by accident when for example trying to sort the column data.

Actually solution is pretty simple. Just use a custom table header renderer :)

It can be something like this one:
public class UnmovableTableHeader extends JTableHeader {

    public UnmovableTableHeader(TableColumnModel model) {

    public void setDraggedColumn(TableColumn aColumn) {
        super.setDraggedColumn(null); // it does the trick :)


Then it can be set directly on JTable object. Assuming there is somewhere an instance of JTable called table:

TableColumnModel cm = table.getColumnModel();
UnmovableTableHeader th = new UnmovableTableHeader(cm)

That's all - columns cannot be dragged but you can still use them (i.e. sorting).


Anonymous said...

Here's simplier:

unknown said...

Thanks mate!

Post a Comment