使用FXML登录java JavaFX
我用Eclipse做了一个简单的登录窗口(Main.java、application.css、login.fxml) 如何在2个按钮上添加侦听器
梅因。爪哇
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("LOGIN");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
登录。fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.layout.HBox?>
<GridPane xmlns:fx="http://javafx.com/fxml/1" hgap="10" vgap="10">
<padding>
<Insets top="10" right="10" bottom="10" left="10"/>
</padding>
<children>
<Label text="Username:" GridPane.columnIndex="0"
GridPane.rowIndex="0" GridPane.halignment="RIGHT" />
<Label text="Password:" GridPane.columnIndex="0"
GridPane.rowIndex="1" GridPane.halignment="RIGHT" />
<TextField GridPane.columnIndex="1" GridPane.rowIndex="0"/>
<PasswordField GridPane.columnIndex="1" GridPane.rowIndex="1" />
<HBox GridPane.columnIndex="0" GridPane.rowIndex="2"
GridPane.columnSpan="2" alignment="CENTER" spacing="10">
<children>
<Button text="Login" />
<Button text="Annulla" />
</children>
</HBox>
</children>
</GridPane>
应用程序。css
/* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */
.label {
-fx-text-fill: rgb(255,0,0);
-fx-font-weight: bold;
-fx-font-style: italic;
}
我需要获得用户名e密码并连接到数据库
# 1 楼答案
您需要定义一个controller class
您可以通过注释控件
@FXML
将控件注入控制器实例,并且可以将控制器中的方法与按钮的处理程序相关联:在FXML中,在根元素上使用
fx:controller
指定用于创建控制器的类。使用fx:id
将元素注入控制器,并使用onAction="#methodName"
为按钮上的操作指定处理程序方法: