package a;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Main extends Application {
public static boolean login(String username, String password) {
boolean b = false;
try {
Class.forName("org.sqlite.JDBC");
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:mydata.sqlite3")) {
try (PreparedStatement ps = conn
.prepareStatement("select count(*) from t_user where username = ? and password = ?")) {
ps.setString(1, username);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int i = rs.getInt(1);
if (i > 0) {
b = true;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
public void start(Stage stage) {
Label lbl_userlogin = new Label("用户登录");
Label lbl_username = new Label("用户名:");
Label lbl_password = new Label("密码:");
TextField txt_username = new TextField();
PasswordField pwf_password = new PasswordField();
Button btn_login = new Button("登录");
Button btn_cancel = new Button("取消");
Font f = new Font(20);
lbl_userlogin.setFont(f);
lbl_username.setFont(f);
lbl_password.setFont(f);
txt_username.setFont(f);
pwf_password.setFont(f);
btn_login.setFont(f);
btn_cancel.setFont(f);
btn_login.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent ae) {
String username = txt_username.getText();
String password = pwf_password.getText();
if (login(username, password)) {
System.out.println("登录成功");
} else {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("登录失败");
alert.setHeaderText("用户名或者密码错误");
alert.setContentText("请输入正确的用户名和密码");
alert.showAndWait();
}
}
});
btn_cancel.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent ae) {
stage.close();
}
});
GridPane gridPane = new GridPane();
Scene scene = new Scene(gridPane);
gridPane.addRow(0, new Label(), lbl_userlogin);
gridPane.addRow(1, lbl_username, txt_username);
gridPane.addRow(2, lbl_password, pwf_password);
gridPane.addRow(3, btn_login, btn_cancel);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
javafx登录界面
最新推荐文章于 2024-11-06 14:58:46 发布