欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javafx 四、使用controller

程序员文章站 2022-03-30 21:56:03
...

1、.fxml中添加id

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>

<GridPane fx:id="root" alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.Controller">
   <columnConstraints>
      <ColumnConstraints />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints />
   </rowConstraints>
   <children>
      <Pane fx:id="root_view" prefHeight="600" prefWidth="900">
         <children>
            <Label layoutX="150.0" layoutY="567.0" prefHeight="23.0" prefWidth="68.0" text="用户名: " />
            <Label layoutX="400.0" layoutY="571.0" text="密码 : " />
            <Button fx:id="btn_login" onAction="#onLogin" layoutX="750.0" layoutY="567.0" mnemonicParsing="false" text="登录" />
            <TextField fx:id="userName" layoutX="200.0" layoutY="567.0" />
            <TextField fx:id="password" layoutX="450.0" layoutY="567.0" />
         </children>
      </Pane>
   </children>
</GridPane>

controller

通过注解 @FXML来自动查找id
布局中 :onAction="#onLogin" 来指定事件操作的方法
controller中定义的方法需与上边相同,并且@FXML

package sample.controller;

import com.jfoenix.controls.JFXSnackbar;
import com.jfoenix.controls.JFXSnackbarLayout;
import com.sun.deploy.util.StringUtils;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import sample.utils.StringUtil;

public class Controller {
    @FXML
    private ImageView iv_login;

    @FXML
    private Button btn_login;

    @FXML
    private TextField password;

    @FXML
    private TextField userName;

    @FXML
    private Pane root;

    @FXML
    private Pane root_view;

    @FXML
    public void onLogin(){
        String userNameText = userName.getText();
        String passwordText = password.getText();

        if(StringUtil.isEmpty(userNameText)){
            JFXSnackbar snackbar = new JFXSnackbar(root_view);
            snackbar.fireEvent(new JFXSnackbar.SnackbarEvent(new JFXSnackbarLayout("请输入用户名")));
            return;
        }

        if(StringUtil.isEmpty(passwordText)){
            JFXSnackbar snackbar = new JFXSnackbar(root_view);
            snackbar.fireEvent(new JFXSnackbar.SnackbarEvent(new JFXSnackbarLayout("请输入密码")));
            return;
        }
    }

}

运行

javafx 四、使用controller

相关标签: javafx