Article : Selecting a JTable Column

Selecting a JTable Column

I currently have JTable in which I wish to allow only row selection

by the user (as per default), however I also wish to allow the user

to click on a table column header item to select (& highlight) the

entire column. (If the user subsequently attempts a selection in the

table it should only allow them to select rows again)

My problem is that is that in order to allow a column to be

selected i need to use:

table.setColumnSelectionAllowed(true);

table.setRowSelectionAllowed(false);

But this now means that the user can ONLY select columns from now

on! Doh!!

In my mouse listener (which listens for clicks on the table header

and identifies the selected columnIdx) I tried this rather unsubtle

approach:

table.setColumnSelectionAllowed(true);

table.setRowSelectionAllowed(false);

table.clearSelection();

table.setColumnSelectionInterval(columnIdx,columnIdx);

table.setColumnSelectionAllowed(false);

table.setRowSelectionAllowed(true);

...but rather predictably this immediately deselected the column!!

I believe a possible solution may be to use:

table.setColumnSelectionAllowed(true);

table.setRowSelectionAllowed(false);

table.clearSelection();

table.setColumnSelectionInterval(columnIdx,columnIdx);

....and then use a mouse listener on the JTable to listen for mouse

clicks (to indicate a new user selection is about to start) and

immediately go:

table.setColumnSelectionAllowed(false);

table.setRowSelectionAllowed(true);

- See more at: file:///H:/New%20Folder/java/Java%20Table/dbin%20jtable/Selecting%20a%20JTable%20Column%20-%20Java%20Forum.htm#sthash.e25aleHX.dpuf

Hi Kenneth,

I had the same issue, and I spent a lot of time by searching for answer, when I found your post. This led me to solve this problem, and you almost solved it too. The last step should be creating a custom celleditor (extends DefaultCellEditor), and overriding the getTableCellEditorComponent() method, put these into the first two line:

table.setColumnSelectionAllowed(false);

table.setRowSelectionAllowed(true);

The full method:

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {

table.setColumnSelectionAllowed(false);

table.setRowSelectionAllowed(true);

return super.getTableCellEditorComponent(table, value, isSelected, row, column);

}

So when you click inside a cell, not the header, the cell editor will set the selection as desired.

I hope you will manage to solve your problem like I did. :)

Best,

Anita - See more at: file:///H:/New%20Folder/java/Java%20Table/dbin%20jtable/Selecting%20a%20JTable%20Column%20-%20Java%20Forum.htm#sthash.e25aleHX.dpuf