JavaFX ContextMenu如何获取被单击的对象? [英] JavaFX ContextMenu how do I get the clicked Object?
本文介绍了JavaFX ContextMenu如何获取被单击的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习javafx.scene.control.ContextMenu,现在我面临一个问题:
I am learning javafx.scene.control.ContextMenu, and right now I am facing a problem:
如何从EventHandler中获取被单击的对象?
how do I get the clicked Object from EventHandler? both event.source() and event.target() return the MenuItem.
让我用一个例子解释一下:
我应该在函数句柄中写什么?
let me explain with an example: what should I write inside the function handle?
TextField text = new TextField();
Label label1 = new Label("hello");
Label label2 = new Label("world");
Label label3 = new Label("java");
ContextMenu menu = new ContextMenu();
MenuItem item = new MenuItem("copy to text field");
menu.getItems().add(item);
item.setOnAction(new EventHandler(){
public void handle(Event event) {
//I want to copy the text of the Label I clicked to TextField
event.consume();
}
});
label1.setContextMenu(menu);
label2.setContextMenu(menu);
label3.setContextMenu(menu);
编辑:我希望有一些简单的解决方案(一个班轮),但如果没有
I was hoping there was some simple solution (one liner), but if there isn't then there are lot's of complex way to do it.
推荐答案
您可以创建自己的ContextMenu实例并将操作父添加到以便进一步参考:
You could create your own instance of ContextMenu and add the action parent to it for further reference:
public class Main extends Application {
TextField text = new TextField();
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
Label label1 = new Label("hello");
Label label2 = new Label("world");
Label label3 = new Label("java");
label1.setContextMenu(new MyContextMenu(label1));
label2.setContextMenu(new MyContextMenu(label2));
label3.setContextMenu(new MyContextMenu(label3));
HBox root = new HBox();
root.getChildren().addAll(text, label1, label2, label3);
Scene scene = new Scene(root, 300, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
private class MyContextMenu extends ContextMenu {
public MyContextMenu(Label label) {
MenuItem item = new MenuItem("copy to text field");
item.setOnAction(event -> {
// I want to copy the text of the Label I clicked to TextField
text.setText(label.getText());
event.consume();
});
getItems().add(item);
}
}
}
这篇关于JavaFX ContextMenu如何获取被单击的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文