阻止JTree选择变化的最佳方式发生? [英] Best way to stop a JTree selection change from happening?

查看:160
本文介绍了阻止JTree选择变化的最佳方式发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对话框,JTree中的每个条目在其他面板中都有相应的选项,当选择发生变化时,它将被更新。如果其中一个条目的选项设置为无效状态,当用户尝试更改为树中的其他条目时,我希望有一个错误对话框,并且选择不会更改。



我尝试在JTree上使用一个valueChangeListener来执行此操作,但是如果有错误,则现在必须将valueChanged方法调用setSelectionRow到旧的选择。所以我没有得到一个StackOverflow,我设置一个布尔isError为true之前,我这样做,以便我可以忽略新的valueChanged事件。不知怎的,我有直觉,这不是最好的解决方案。 ; - )



我该怎么办?对于这样的情况,是否有很好的设计模式?

解决方案

不确定是最佳做法,但也许您可以将FocusListener您要验证的组件...在调用事件时调用验证,然后如果您不希望由于验证失败而移动焦点,则会消耗事件?



稍后编辑:



至少与java 8(我没有检查较早版本)此解决方案将无法正常工作,因为FocusEvent不会成为一个低级别的事件。因此它不能消耗。请参阅方法AWTEvent.consume()


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 entries is set to an invalid state, when the user attempts to change to a different entry in the tree, I want there to be an error dialog and have the selection not change.

I tried doing this with a valueChangeListener on the JTree, but currently then have to have the valueChanged method call "setSelectionRow" to the old selection if there is an error. So that I don't get a StackOverflow, I set a boolean "isError" to true before I do this so that I can ignore the new valueChanged event. Somehow I have the gut feeling this is not the best solution. ;-)

How would I go about it instead? Is there a good design pattern for situations like this?

解决方案

Not sure it's best practice, but maybe you could put a FocusListener on the component(s) you want to validate... call your validation when the event is called and then consume then event if you don't want the focus to be moved because the validation fails?

Later Edit:

At least with java 8 (I didn't check earlier versions) this solution won't work, because the FocusEvent appears not to be a low-level event. Hence it cannot be consumed. See Method AWTEvent.consume()

这篇关于阻止JTree选择变化的最佳方式发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆