Best way to stop a JTree selection change from happening?

前端 未结 7 2180
傲寒
傲寒 2021-01-06 05:07

I have a dialog where each entry in a JTree has its corresponding options in a different panel, which is updated when the selection changes. If options for one of the entrie

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 05:31

    Stumbled across this thread while investigating a solution for the same problem. First, let me tell you things that didn't work. I attempted to register MouseListeners and all of that with the tree. The problem was that the TreeUI's mouse listeners were getting to the process the event before my JTree did, meaning it was too late to set a flag or anything like that. Besides that this solution produced some ugly code and I would generally avoid it.

    So now for the actual solution!
    After using a few Thread.dumpStack() calls to get a stack dump, I found the method I was looking to override. I extended the BasicTreeUI and overrode the "protected void selectPathForEvent(TreePath path, MouseEvent event)".

    This will give you access to the mouse event that caused the selection before the selection actually occurs. You can then use whatever logic you need to either event.consume() and return if you want to stop the selection, do whatever selection you want or pass it up for default processing by calling super.selectPathForEvent(path, event);

    Just remember to set the UI you created in JTree. That mistake wasted a few minuets of my life ;-)

提交回复
热议问题