How to keep a single column from being reordered in a JTable?

前端 未结 8 1792
时光说笑
时光说笑 2020-11-30 09:17

I have a JTable and I need to be able to reorder the columns. However I want the first column to not be able to be re-ordered. I used the following to enable re

8条回答
  •  [愿得一人]
    2020-11-30 09:48

    First you need to define a better and simpler way. What don't you like about the 2 table approach?

    You can't use a TableColumnModelListener, because the event is fired "after" the column has already been moved.

    The code for dragging the column is found in the BasicTableHeaderUI. So you could try overriding the code there, but then you would need to do it for all LAFs.

    The above code invokes JTableHeader.getReorderingAllowed() on a mousePressed event to determine if column reordering is allowed. I guess you could override that method in the JTableHeader and perhaps use the MouseInfo class to get the current mouse location to determine if it was over the first column and then return false. But then now you would also need to create a custom JTable that uses the custom table header.

    Of course with either of the above suggestions you might be able to prevent the first column from being moved. But don't forget you also need to prevent the 2nd column from being inserted before the first column. I don't believe there is a short simple answer to the question.

    Fixed Column Table is my version of how this would be imlemented with two tables. Is it better? I don't know, but it is simple since its only a single line of code to use it.

提交回复
热议问题