加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在JavaFX控制器中获取被单击对象的id的更好方法

发布时间:2020-12-15 05:11:52 所属栏目:Java 来源:网络整理
导读:我正在寻找一种更好的方法来获取此对象的事件处理程序中被点击对象的id. 我已经发现了这个: javafx pass fx:id to controller or parameter in fxml onAction method 但这对我不起作用. 现在我正在使用节点类的getId()函数,如下所示: Button btn = (Button
我正在寻找一种更好的方法来获取此对象的事件处理程序中被点击对象的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之间的控件,因此这个答案考虑到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());
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读