gpt4 book ai didi

java - 如何给自定义控件添加监听器?

转载 作者:行者123 更新时间:2023-12-01 14:15:02 25 4
gpt4 key购买 nike

我想向我的自定义控件添加一个选择监听器,该控件包含几个按钮,以便每当单击按钮时该控件都应执行特定功能。问题是:我想将监听器添加到控件本身,而不是单独添加到其每个子按钮。我该怎么办?

最佳答案

摘自文章Creating Your Own Widgets using SWT :

SWT Event Mechanism

SWT provides a low-level listener mechanism as well as the usual Java ‘typed’ listeners. Every SWT widget understands addListener(int eventType, Listener listener) and notifyListeners(int eventType, Event event). The eventType constants are defined in class SWT. When an event occurs, the widget creates an SWT Event object containing the appropriate type constant. The notifyListeners method calls handleEvent(Event event) for the Listener. If you need to reuse an existing SWT event, you would typically use this mechanism.

For example, if your widget implements a selection event, you could implement your ‘typed’ add and remove methods as follows:

public void addSelectionListener(SelectionListener listener) {
addListener(SWT.Selection, new TypedListener(listener));
}

public void removeSelectionListener(SelectionListener listener) {
removeListener(SWT.Selection, listener);
}

When the ‘selection event’ occurs in your widget (say, when child1 is selected), you notify the application’s selection listeners using notifyListeners.

child1.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
notifyListeners(SWT.Selection, new Event());
}
});

Note that when we add the listener we first wrap it in a TypedListener. This is because TypedListener’s handleEvent(Event event) method creates the appropriate TypedEvent subclass based on the type in the Event, and then calls the appropriate method for the typed event. In this way, applications can add Java typed listeners to widgets, but widget implementations can use the more efficient low-level listener mechanism. Make sure that your widget implementation provides a typed listener API, however. Applications should not be calling low-level listener methods. The typed listener methods prevent accidental programming errors such as assuming that all widgets can handle all types of event, or that all fields in the Event class are valid for all events.

关于java - 如何给自定义控件添加监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182130/

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