簡體   English   中英

如何聽焦點兒童事件

[英]How to listen focusing child event

這是我的代碼:

@Override
void start(Stage stage) throws Exception {
    def root = new VBox() {
        {
            children.add(new TextArea() {
                {
                    setId("ta1")
                }
            })
            children.add(new TextArea() {
                {
                    setId("ta2")
                }
            })
        }
    }
    root.setOnFocus(new OnFocus() {
        void onFocus(Node focusedTarget) {
            // handle focusedTarget
        }
    })
    def scene = new Scene(root, 800, 600)
    stage.setScene(scene)
    stage.show()
}

我希望實現以下代碼來處理聚焦子事件

root.setOnFocus(new OnFocus() {
            void onFocus(Node focusedTarget) {
                // handle focusedTarget
            }
        })

如果我設置了#ta1和#ta2的focusedProperty,如果孩子大的話,很難做到,所以我希望直接聽父母的話,怎么辦?

標准事件調度可用於在Scene上觸發自定義事件。 focusOwnerScenefocusOwner屬性的偵聽器可用於觸發事件。

示例 (java)

public class FocusEvent extends Event {

    public static final EventType FOCUS_EVENT_TYPE = new EventType(EventType.ROOT);

    public FocusEvent(Object source, EventTarget target) {
        super(source, target, FOCUS_EVENT_TYPE);
    }

}
@Override
public void start(Stage primaryStage) {
    TextArea ta1 = new TextArea();
    ta1.setId("ta1");
    TextArea ta2 = new TextArea();
    ta2.setId("ta2");
    VBox root = new VBox(ta1, ta2);
    root.addEventHandler(FocusEvent.FOCUS_EVENT_TYPE, evt -> {
        System.out.println("focused "+ evt.getTarget());
    });

    ta1.addEventHandler(FocusEvent.FOCUS_EVENT_TYPE, evt -> {
        System.out.println("You focused the first TextArea");
        evt.consume();
    });

    Scene scene = new Scene(root);
    scene.focusOwnerProperty().addListener((o, old, newValue) -> {
        if (newValue != null) {
            FocusEvent event = new FocusEvent(scene, newValue);
            Event.fireEvent(newValue, event);
        }
    });

    primaryStage.setScene(scene);
    primaryStage.show();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM