JavaFX控制器:设置按钮点击事件代码示例

最终效果

JavaFX控制器:设置按钮点击事件代码示例

场景编辑

JavaFX控制器:设置按钮点击事件代码示例

代码

pom

<build>
        <finalName>HelloJavaFX</finalName>
        <resources>
            <resource>
                <!-- 这里是放在 src/main/java-->
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.fxml</include>
                    <include>**/fxml/*.fxml</include>
                    <!-- 如果想要弄个包名专门放fxml文件,像上一行这样添加设置 -->
                    <!-- 之后,使用getResource("fxml/xx.fxml")这样子 -->
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
 </build>

fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="cn.zxl.Controller.Controller">
   <children>
      <Button layoutX="273.0" layoutY="189.0" mnemonicParsing="false" text="我是按钮" onAction="#test"/>
   </children>
</AnchorPane>

java代码

Controller

package cn.zxl.Controller;

/**
 * @Description: //TODO 控制器类
 * @Author: zhangxueliang
 * @Create: 2021-05-27 11:35
 * @Version: 1.0
 **/
public class Controller {
    public void test(){
        System.out.println("点击了按钮");
    }
}

启动类

package cn.zxl.Controller;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 * @Description: //TODO 建立FXML
 * @Author: zhangxueliang
 * @Create: 2021-05-27 11:16
 * @Version: 1.0
 **/
public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(this.getClass().getResource("sample.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

 

上一篇:JavaFX FXML场景编辑器使用示例


下一篇:javaswing和javafx