JavaFX 2.0 - 为FXML中的自定义组件创建操作处理程序

时间:2012-04-01 13:10:47

标签: custom-controls javafx-2 fxml

我想在我的新组件中添加自定义操作。 怎么做?

示例代码:

组件

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? :-(  */
            }
        });
    }
}

控制器

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>

寻求帮助

1 个答案:

答案 0 :(得分:6)

您需要在自定义组件中实现属性,该属性将存储您的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文件中添加导入:

<?import my.package.MyCustomComponent?>