JavaFX 2.0-为FXML中的自定义组件创建操作处理程序 [英] JavaFX 2.0 - create action handler for custom component in FXML

查看:207
本文介绍了JavaFX 2.0-为FXML中的自定义组件创建操作处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的新组件中添加一个自定义动作。
如何做到?

I want to add a custom action in my new component. How to do this?

示例代码:

组件

public class MyCustomComponent extends Region {
    public MyCustomComponent(){
        super();

        this.setOnMouseClicked(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                /* throw my custom event here and handle it in my FXML controller - but how? :-(  */
            }
        });
    }
}

Controller

Controller

public class MyController {
    @FXML protected void myCustomAction(ActionEvent event) {
        // do something
    }
}

FXML:

<BorderPane fx:controller="fxmlexample.MyController" 
    xmlns:fx="http://javafx.com/fxml">
     <top>
        <MyCustomComponent onAction="#myCustomAction">
        </MyCustomComponent>
     </top>
</BorderPane>

Thx for帮助

推荐答案

您需要实现自定义组件中的t属性,它将存储您的操作

You need to implement property in your custom component, which will store your action.

public class MyCustomComponent extends Region {
    public MyCustomComponent(){
        super();

        // just to find out where to click
        setStyle("-fx-border-color:red;");
        setPrefSize(100, 100);

        this.setOnMouseClicked(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                onActionProperty().get().handle(event);
            }
        });
    }

    // notice we use MouseEvent here only because you call from onMouseEvent, you can substitute any type you need
    private ObjectProperty<EventHandler<MouseEvent>> propertyOnAction = new SimpleObjectProperty<EventHandler<MouseEvent>>();

    public final ObjectProperty<EventHandler<MouseEvent>> onActionProperty() {
        return propertyOnAction;
    }

    public final void setOnAction(EventHandler<MouseEvent> handler) {
        propertyOnAction.set(handler);
    }

    public final EventHandler<MouseEvent> getOnAction() {
        return propertyOnAction.get();

    }    
}

不要忘记添加导入您的fxml文件:

and don't forget to add import in your fxml file:

<?import my.package.MyCustomComponent?>

这篇关于JavaFX 2.0-为FXML中的自定义组件创建操作处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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