Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 1. Create first this database to your MySQL server:
- create schema javafxsample;
- use javafxsample;
- create table if not exists user(
- id int(11) not null auto_increment,
- username varchar(255) not null unique,
- last_name varchar(255) not null,
- first_name varchar(255) not null,
- password varchar(255) not null,
- created_at datetime not null default current_timestamp,
- primary key(id)
- );
- 2. Add mysql-connector-java-6.0.6.jar to your dependencies.
- 3. Update database credentials on Database.class.
- */
- package io.github.julianjupiter.javafx;
- import java.io.Serializable;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javafx.application.Application;
- import javafx.geometry.Insets;
- import javafx.geometry.Pos;
- 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.layout.HBox;
- import javafx.scene.text.Font;
- import javafx.scene.text.FontWeight;
- import javafx.scene.text.Text;
- import javafx.stage.Stage;
- public class JApps extends Application {
- private static final Logger logger = Logger.getLogger(JApps.class.getName());
- private UserRepository userRepository = new UserRepository();
- @Override
- public void start(Stage primaryStage) {
- primaryStage.setTitle("JavaFX Welcome");
- GridPane grid = new GridPane();
- grid.setAlignment(Pos.CENTER);
- grid.setHgap(10);
- grid.setVgap(10);
- grid.setPadding(new Insets(25, 25, 25, 25));
- Text scenetitle = new Text("Add User");
- scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
- grid.add(scenetitle, 0, 0, 2, 1);
- Label userNameLabel = new Label("Username:");
- grid.add(userNameLabel, 0, 1);
- TextField usernameTextField = new TextField();
- grid.add(usernameTextField, 1, 1);
- Label lastNameLabel = new Label("Last Name:");
- grid.add(lastNameLabel, 0, 2);
- TextField lastNameTextField = new TextField();
- grid.add(lastNameTextField, 1, 2);
- Label firstNameLabel = new Label("First Name:");
- grid.add(firstNameLabel, 0, 3);
- TextField firstNameTextField = new TextField();
- grid.add(firstNameTextField, 1, 3);
- Label passwordLabel = new Label("Password:");
- grid.add(passwordLabel, 0, 4);
- PasswordField passwordField = new PasswordField();
- grid.add(passwordField, 1, 4);
- Button saveButton = new Button("Save");
- HBox hBox = new HBox(10);
- hBox.setAlignment(Pos.BOTTOM_RIGHT);
- hBox.getChildren().add(saveButton);
- grid.add(hBox, 1, 5);
- saveButton.setOnAction(actionEvent -> {
- String username = usernameTextField.getText().trim();
- String lastName = lastNameTextField.getText().trim();
- String firstName = firstNameTextField.getText().trim();
- String password = passwordField.getText();
- if (!StringPool.BLANK.equals(username) && !StringPool.BLANK.equals(lastName) && !StringPool.BLANK.equals(firstName) && !StringPool.BLANK.equals(password)) {
- try {
- if (!userRepository.userExists(username)) {
- User user = this.createUserObject(username, lastName, firstName, password);
- int userId = userRepository.saveUser(user);
- if (userId > 0) {
- this.alert("Save", "Successful!", AlertType.INFORMATION);
- } else {
- this.alert("Error", "Failed!", AlertType.ERROR);
- }
- } else {
- this.alert("Error", "User already exists!", AlertType.ERROR);
- }
- } catch (Exception exception) {
- logger.log(Level.SEVERE, exception.getMessage());
- }
- } else {
- this.alert("Error", "Please complete fields!", AlertType.ERROR);
- }
- });
- Scene scene = new Scene(grid, 300, 275);
- primaryStage.setScene(scene);
- primaryStage.show();
- }
- public void alert(String title, String message, AlertType alertType) {
- Alert alert = new Alert(alertType);
- alert.setTitle(title);
- alert.setHeaderText(null);
- alert.setContentText(message);
- alert.showAndWait();
- }
- public User createUserObject(String username, String lastName, String firstName, String password) {
- User user = new User();
- user.setUsername(username);
- user.setLastName(lastName);
- user.setFirstName(firstName);
- user.setPassword(password);
- return user;
- }
- public static void main(String[] args) {
- launch(args);
- }
- }
- // Domain object
- class User implements Serializable {
- private static final long serialVersionUID = 3789909326487155148L;
- private int id;
- private String username;
- private String lastName;
- private String firstName;
- private String password;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public String getFirstName() {
- return firstName;
- }
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- // Data access/repository
- class UserRepository {
- private static final Logger logger = Logger.getLogger(UserRepository.class.getName());
- public boolean userExists(String username) throws SQLException {
- Connection connection = null;
- PreparedStatement statement = null;
- List<User> users = new ArrayList<>();
- try {
- connection = Database.getDBConnection();
- connection.setAutoCommit(false);
- String query = "SELECT id, username, last_name, first_name, password FROM user WHERE username = ?";
- statement = connection.prepareStatement(query);
- int counter = 1;
- statement.setString(counter++, username);
- ResultSet resultSet = statement.executeQuery();
- while (resultSet.next()){
- User user = new User();
- user.setId(resultSet.getInt(1));
- user.setUsername(resultSet.getString(2));
- user.setLastName(resultSet.getString(3));
- user.setFirstName(resultSet.getString(4));
- user.setPassword(resultSet.getString(5));
- users.add(user);
- }
- return users.isEmpty() ? false : true;
- } catch (SQLException exception) {
- logger.log(Level.SEVERE, exception.getMessage());
- } finally {
- if (null != statement) {
- statement.close();
- }
- if (null != connection) {
- connection.close();
- }
- }
- return users.isEmpty() ? false : true;
- }
- public int saveUser(User user) throws SQLException {
- Connection connection = null;
- PreparedStatement statement = null;
- ResultSet resultSet = null;
- try {
- connection = Database.getDBConnection();
- connection.setAutoCommit(false);
- String query = "INSERT INTO user(username, last_name, first_name, password) VALUES(?, ?, ?, ?)";
- statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
- int counter = 1;
- statement.setString(counter++, user.getUsername());
- statement.setString(counter++, user.getLastName());
- statement.setString(counter++, user.getFirstName());
- statement.setString(counter++, user.getPassword());
- statement.executeUpdate();
- connection.commit();
- resultSet = statement.getGeneratedKeys();
- if (resultSet.next()){
- return resultSet.getInt(1);
- }
- } catch (SQLException exception) {
- logger.log(Level.SEVERE, exception.getMessage());
- connection.rollback();
- } finally {
- if (null != resultSet) {
- resultSet.close();
- }
- if (null != statement) {
- statement.close();
- }
- if (null != connection) {
- connection.close();
- }
- }
- return 0;
- }
- }
- // Database connection utility
- class Database {
- private static final Logger logger = Logger.getLogger(Database.class.getName());
- private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
- private static final String DB_CONNECTION = "jdbc:mysql://localhost/javafxsample";
- private static final String DB_USER = "root";
- private static final String DB_PASSWORD = "admin";
- public static Connection getDBConnection() throws SQLException {
- Connection connection = null;
- try {
- Class.forName(DB_DRIVER);
- } catch (ClassNotFoundException exception) {
- logger.log(Level.SEVERE, exception.getMessage());
- }
- try {
- connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
- return connection;
- } catch (SQLException exception) {
- logger.log(Level.SEVERE, exception.getMessage());
- }
- return connection;
- }
- }
- // String utility
- class StringPool {
- public static final String BLANK = "";
- }
Add Comment
Please, Sign In to add comment