gpt4 book ai didi

java - 如何使 JTable 单击未选择的内容进行拖动而不是选择

转载 作者:搜寻专家 更新时间:2023-11-01 01:38:11 24 4
gpt4 key购买 nike

如果您使用 table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) 设置了 JTable,然后在尚未选择的行上单击拖动,它会开始选择多行。我们不想要这种行为。我们希望这样,如果您单击一个节点,即使它尚未被选中,它也会开始拖动它。

我们确实需要打开多选模式,因此将其设置为单选(这确实会导致我们想要的行为)不是一个选项。

更新:在这一点上,它似乎需要某种丑陋的 hack,因为逻辑在私有(private)方法 BasicTableUI$Handler.canStartDrag 中

最佳答案

我找到了一种可能的解决方案。您将鼠标监听器括起来,这样您就可以在 canStartDrag 调用期间欺骗对 isCellSelected 的调用。

子类 JTable(或者在我的例子中,JXTreeTable)。在构造函数中调用这个:

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

然后你需要这个:

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

这在很多方面都是一个丑陋的 hack,但是......现在它似乎有效。

关于java - 如何使 JTable 单击未选择的内容进行拖动而不是选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5969258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com