gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:49:39 25 4
gpt4 key购买 nike

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

示例代码:

组件

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

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>

谢谢帮助

最佳答案

您需要在您的自定义组件中实现属性,它将存储您的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?>

关于custom-controls - JavaFX 2.0 - 为 FXML 中的自定义组件创建操作处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9964638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com