使用FXML登录JavaFX
我用Eclipse做了一个简单的登录窗口(Main.java、application.css、login.fxml) 如何在2个按钮上添加侦听器 Main.java使用FXML登录JavaFX,java,css,javafx,fxml,Java,Css,Javafx,Fxml,我用Eclipse做了一个简单的登录窗口(Main.java、application.css、login.fxml) 如何在2个按钮上添加侦听器 Main.java package application; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.
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);
}
}
Login.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>
我需要获取用户名e密码并连接到数据库您需要定义一个密码
您可以通过注释将控件注入控制器实例@FXML
,并且可以将控制器中的方法与按钮的处理程序相关联:
package application ;
public class LoginController {
@FXML
private TextField userIdField ;
@FXML
private PasswordField passwordField ;
@FXML
private void login() {
String userId = userIdField.getText();
String password = passwordField.getText();
// etc...
}
}
在FXML中,在根元素上使用fx:controller
指定用于创建控制器的类。使用fx:id
将元素注入控制器,并使用onAction=“#methodName”
为按钮上的操作指定处理程序方法:
package application ;
public class LoginController {
@FXML
private TextField userIdField ;
@FXML
private PasswordField passwordField ;
@FXML
private void login() {
String userId = userIdField.getText();
String password = passwordField.getText();
// etc...
}
}