bittramp
bittramp

Reputation: 131

How can I turn off jtable cell selection through mouse presses and drags

I am wanting to use a JTable but with a different cell selection method rather than clicking in the cells. I am using the glasspane to allow users to draw a rectangle and am discovering what cells are contained in the rectangle to select. But I am only wanting to select a cell if it is totally within the rectangle. For example, imagine a simple 3 x 3 table. The user my want to select the middle cell (1,1). I want them to be able to click in the first cell 0,0 and drag down to cell 2,2 drawing the rectangle for selection. But I don't want cells 0,0 or 2,2 selected. Or get all 9 selected, for that matter. This is a simplified example. Drawing the rectangle might actually encompass cells from more than one table on the screen.

I looked into implementing the ListSelectionModel interface, but don't really want to try and rewrite that. While experimenting I saw that setSelectionInterval() in the model was being called like crazy (for every single mouse movement) as I click and dragged around in the table. What I would really like is to find a simple way to turn off whatever listener/mechanism is on the table that makes the calls to the SelectionModel, while keeping the model in place. I'd still want it to report isSelectedIndex() for example. I would tell the model what intervals are selected.

I figured that somewhere there's a mouse input adapter inherently built into JTables? I'd like to turn it off if possible.

Thanks, BBB

Upvotes: 4

Views: 2893

Answers (1)

eternaln00b
eternaln00b

Reputation: 1053

For a generic / text-based question, you get a generic, text-based response. :) Start by uninstalling the MouseListeners installed on the table by default:

MouseListener[] listeners = myTable.getMouseListeners();
for (MouseListener l : listeners)
{
    myTable.removeMouseListener(l);
}

Then, add your own MouseListener to the table (use MouseAdapter if you want) and override the "mousePressed" / "mouseReleased" methods to record the points where the drag began, and drag ended. Determine the enclosing rectangle and call:

setRowSelectionInterval(#, #)
setColumnSelectionInterval(#,#)

to select one (or more) cells.

Upvotes: 4

Related Questions