首页 {{menuItem.firstTitle}} {{menuItem.secondTitle}}

javafx fxml中设置点击事件并获取控件的id设置Button值

2018年12月29日 105

一、fxml中设置点击事件

关键代码onMouseClicked="#onButtonClick"

      <Button mnemonicParsing="false" fx:id="mButton"  onMouseClicked="#onButtonClick" 
text="文件" GridPane.columnIndex="1" GridPane.rowIndex="2" />

二、代码中绑定点击事件并做处理

新增onButtonClick

 @FXML
    private void onButtonClick(){
        //绑定点击事件 函数名必需与fxml中的一致
        System.out.println("https://www.it399.com");
        //mButton.setText("在线助手");
    }

注意这段代码必须在相应的Controller中

图片.png

不然会报如下错误:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javafx.fxml.LoadException: Error resolving onMouseClicked='#onButtonClick', 
either the event handler is not in the Namespace or there is an error in the script.
/H:/csy/my_project/java/JavaFxDemo/out/production/JavaFxDemo/sample/sample.fxml:24

三、获取控件id点击之后改变按钮值

@FXML
private Button mButton;// fx:id="mButton",不能使用id= "mButton"

这样就实现了在代码中fxml中的绑定

mButton.setText("在线助手 https://www.it399.com");
转载请注明:原文链接 https://www.it399.com/article?id=60
相关文章 全部

扫一扫,体验小程序

线助手小程序
-
-
-
Copyright © 2017-2018 . All Rights Reserved.

粤ICP备18008506号