Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Selecting a JTable Column

  Asked By: Kenneth    Date: Jul 08    Category: Java    Views: 3256
  

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);


However I'm a bit of a newbie and how this might be implemented is
beyond my current knowledge, plus this approach is probably flawed!

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Anita Karacs     Answered On: Aug 08

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

 
Didn't find what you were looking for? Find more on Selecting a JTable Column Or get search suggestion and latest updates.




Tagged: