我正在寻找一种更好的方法来获取该对象的事件处理程序中单击的对象的 id。
我已经找到了这个:
javafx 将 fx:id 传递给控制器或 fxml onAction 方法中的参数
但这对我不起作用。
现在我使用节点类的 getId() 函数,如下所示:
Button btn = (Button) event.getSource();
String id = btn.getId();
但我想不仅仅将这种方法用于按钮。
由于 fx:id 用于绑定 FXML 和 Controller 之间的控件,因此这个答案考虑到 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());
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)