Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JTable click on unselected do a drag instead of a select

Tags:

java

swing

If you have JTable set with table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) and then you click drag on a row that is not already selected, it starts selecting multiple rows. We don't want that behavior. We want it so if you click on a node, even if it's not already selected, it will start dragging it.

We do need the multi select mode on, so setting it to single select (which does result in the behavior we want) is not an option.

Update: At this point, it appears it will require some type of ugly hack since the logic is in a private method BasicTableUI$Handler.canStartDrag

like image 464
mentics Avatar asked Jan 19 '23 18:01

mentics


1 Answers

I found one possible solution. You bracket the mouse listeners so you can lie to the call to isCellSelected during the canStartDrag call.

Subclass JTable (or in my case, JXTreeTable). In the constructor call this:

private void setupSelectionDragHack()
{
    // Bracket the other mouse listeners so we may inject our lie
    final MouseListener[] ls = getMouseListeners();
    for (final MouseListener l : ls)
    {
        removeMouseListener(l);
    }
    addMouseListener(new MouseAdapter()
    {
        @Override
        public void mousePressed(final MouseEvent e)
        {
            // NOTE: it might not be necessary to check the row, but... I figure it's safer maybe?
            mousingRow = rowAtPoint(e.getPoint());
            mousingInProgress = true;
        }
    });
    for (final MouseListener l : ls)
    {
        addMouseListener(l);
    }
    addMouseListener(new MouseAdapter()
    {
        @Override
        public void mousePressed(final MouseEvent e)
        {
            mousingInProgress = false;
        }
    });
}

And then you'll need this:

@Override
public boolean isCellSelected(final int row, final int column)
{
    if (mousingInProgress && row == mousingRow)
    {
        // Only lie to the canStartDrag caller. We tell the truth to everyone else.
        final StackTraceElement[] elms = Thread.currentThread().getStackTrace();
        for (int i = 0; i < 3; i++)
        {
            if (elms[i].getMethodName().equals("canStartDrag"))
            {
                return mousingInProgress;
            }
        }
    }
    return super.isCellSelected(row, column);
}

It's an ugly hack in many ways, but... for now it seems to work.

like image 99
mentics Avatar answered Jan 31 '23 00:01

mentics