gpt4 book ai didi

java - 在 JavaFX Controller 中获取被单击对象的 ID 的更好方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:58 25 4
gpt4 key购买 nike

我正在寻找一种更好的方法来在该对象的事件处理程序中获取被单击对象的 ID。

我已经找到了:

javafx pass fx:id to controller or parameter in fxml onAction method

但这对我不起作用。

现在我像这样使用节点类的 getId() 函数:

Button btn = (Button) event.getSource();
String id = btn.getId();

但我想将此方法不仅用于按钮。

最佳答案

由于 fx:id 用于在 FXML 和 Controller 之间绑定(bind)控件,因此此答案考虑到 OP 在单击时需要控件的 id

import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class IdForControlsOnClick extends Application{

@Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
VBox vBox = new VBox(20);
borderPane.setCenter(vBox);

Button button = new Button("Hi");
button.setId("Button");
Label label = new Label("Label");
label.setId("Label");
CheckBox checkBox = new CheckBox();
checkBox.setId("CheckBox");

button.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
label.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());
checkBox.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler());

vBox.getChildren().addAll(button, label, checkBox);
Scene scene = new Scene(borderPane, 200, 200);
stage.setScene(scene);
stage.show();

}

public static void main(String[] args) {
launch(args);
}

private class MyEventHandler implements EventHandler<Event>{
@Override
public void handle(Event evt) {
System.out.println(((Control)evt.getSource()).getId());
}
}
}

关于java - 在 JavaFX Controller 中获取被单击对象的 ID 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24302636/

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