这是我的代码:

@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上触发自定义事件。可以使用到达focusOwnerScene属性的侦听器来触发事件。

范例(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();
}

07-27 13:23