我正在尋找一種簡單的方法來製作一個Swing組件將所有收到的 事件轉發給其父容器(或者甚至所有家長,直至根)。Swing:如何實現從子組件到父容器的所有事件轉發?
編輯:
我在哪裏需要這個?我有一個圖編輯器。組件必須轉發按鍵和 鼠標點擊(只要用戶單擊該組件的子元素 ,就自行設置爲「活動」)。
首先,讓我介紹一下我現有的解決方案。這是一個解決方法。
public interface IUiAction {
void perform(Component c);
}
public static void performRecursiveUiAction(Container parent, IUiAction action) {
if (parent == null) {
return;
}
for (Component c : parent.getComponents()) {
if (c != null) {
action.perform(c);
}
}
for (Component c : parent.getComponents()) {
if (c instanceof Container) {
performRecursiveUiAction((Container) c, action);
}
}
}
/**
* 1) Add listener to container and all existing components (recursively).
* 2) By adding a ContainerListener to container, ensure that all further added
* components will also get the desired listener.
*
* Useful example: Ensure that every component in the whole component
* tree will react on mouse click.
*/
public static void addPermanentListenerRecursively(Container container,
final IUiAction adder) {
final ContainerListener addingListener = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
adder.perform(e.getChild());
}
};
// step 1)
performRecursiveUiAction(container, adder);
// step 2)
performRecursiveUiAction(container, new IUiAction() {
@Override
public void perform(Component c) {
if (c instanceof Container) {
((Container) c).addContainerListener(addingListener);
}
}
});
}
用法:
addPermanentListenerRecursively(someContainer,
new IUiAction(
@Override
public void perform(Component c){
c.addMouseListener(somePermanentMouseListener);
}
)
);
通過查看代碼,你會說這是一個很好的概念?
我目前的概念的問題是:它只轉發事件,爲其手動指定偵聽器。
你能推薦一個更好的嗎?
我在某些swing事件上遇到了consume()方法,這個方法用於指示您在處理程序中使用了該事件。我認爲相反的是你需要的。 – akarnokd 2009-06-27 14:27:04
例如:鼠標點擊,鼠標拖動(「激活」視覺圖元素),各種熱鍵,... – 2009-06-27 14:30:20