Swing:有没有办法区分用户引起的ItemEvent和应用程序引起的? [英] Swing: Is there a way to differentiate between a user-caused ItemEvent and an application-caused one?

查看:235
本文介绍了Swing:有没有办法区分用户引起的ItemEvent和应用程序引起的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于Swing的应用程序中的组合框,我很难知道该做什么来区分从用户事件生成的ItemEvent与由应用程序引起的ItemEvent。

I'm working with a combobox in a Swing-based application, and I'm having a hard time figuring out what to do to differentiate between an ItemEvent that is generated from a user event vs one caused by the application.

例如,Lets说我有一个组合框,' combo ',我正在监听itemStateChanged事件my ItemListener,' listener '。当用户将选择更改为项目2或执行行(伪代码):

For instance, Lets say I have a combobox, 'combo' and I'm listening for itemStateChanged events with my ItemListener, 'listener'. When either a user changes the selection to item 2 or I execute the line (pseudocode):

combo.setSelection(2)

..似乎我无法区分这些事件。

.. it seems like I'm not able to tell these events apart.

也就是说,我不是任何方式的Swing专家,所以我想我会问。

That said, I'm no Swing expert by any means, so I thought I would ask.

感谢!

推荐答案

:)。如果您尝试对更改做出反应,则无需区分用户和应用程序。我可以想象只有一个用例,你需要区分。应用程序正在显示某些数据的情况。在这种情况下,您可能拥有应用程序的数据模型。并且在这个模型中还有一些更改侦听器,应用程序GUI将通过设置值到组件来做出反应。并且。如果用户选择任何内容到GUI组件。数据模型将通过改变值来反应。在这种情况下,很容易在数据模型上设置某种只读状态,这将通知模型忽略来自观察对象的任何事件。此通知集应该在EDT中运行,并且标记没有问题。小示例:

The Action and Reaction law is quite clear :). If you try to react on change there is no need to distinguish between user and application. I can imagine only one use case where you need to "distinguish". The case where application is displaying some data. In this case you have, probably, data model for your application. And also there are some change listener in this model and application GUI will react by setting values to components. And also. If user selects anything into GUI component. The data model will react by changing value. In this case it is easy to set up some sort of read-only state on data model which will notify model to ignore ANY event coming from observed objects. This notification set should run in EDT and there is no problem with flagging. Small example:

class ApplicationDataModel {

    private Flag current = Flag.RW;

    public void setData(ApplicationData data) {
        current = Flag.RO;
        setDataImpl(data);
        notifyObservers();
        current = Flag.RW;
    }

    public void reaction(Event e) {
        if (flag = Flag.RO) return;
        ...
    }

}

小心标记,不要忘记线程。如果你正在从另一个线程调用setData然后EDT你会遇到麻烦。当然。提取 ApplicationData 对象必须在不同的线程中运行;)。一般来说,重新思考您的应用程序的设计。

Be careful with flagging and don't forget about threading. If you are calling setData from another thread then EDT you are going into trouble. Of course. The extraction of ApplicationData object has to be run in different thread ;). In general, rethink design of your application.

这篇关于Swing:有没有办法区分用户引起的ItemEvent和应用程序引起的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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