获取JavaFX控制器中单击的Object的id的更好方法 [英] Better way for Getting id of the clicked Object in JavaFX controller

查看:576
本文介绍了获取JavaFX控制器中单击的Object的id的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I`m looking for a better way for getting the id of the clicked object inside the event handler for this object.

我已经找到了这个:

javafx将fx:id传递给fxml onAction方法中的控制器或参数

但这对我不起作用。

现在我正在使用节点类的getId()函数,如下所示:

Now I'm using the getId() function of the node class like this:

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

但我想这个方法不仅仅用于按钮。

But i want to use this method not only for buttons.

推荐答案

由于fx:id用于绑定FXML和Controller之间的控件,这个答案考虑到OP想要 id

Since fx:id is used to bind controls between FXML and Controller, this answer is taking into consideration that OP wants the id of the controls when clicked.

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());
        }
    }
}

这篇关于获取JavaFX控制器中单击的Object的id的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆