By GokiSoft.com| 19:48 24/06/2024|
Java Advanced

[Share Code] Quản lý sách Java FX - C2307L

#App.java


package com.gokisoft.library;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {

    private static Scene scene;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("library"), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

    public static void main(String[] args) {
        launch();
    }

}


#LibraryController.java


package com.gokisoft.library;

import com.gokisoft.models.Books;
import com.gokisoft.models.BooksEntity;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;

public class LibraryController implements Initializable{
    @FXML
    private TextField txtTitle;
    @FXML
    private TextField txtPrice;
    @FXML
    private TextField txtAuthor;
    @FXML
    private Button btnSave;
    @FXML
    private Button btnDelete;
    @FXML
    private Button btnSearch;
    @FXML
    private Button btnClear;
    @FXML
    private TableView<Books> bookView;
    @FXML
    private TableColumn<Books, Integer> id;
    @FXML
    private TableColumn<Books, String> bookName;
    @FXML
    private TableColumn<Books, Float> price;
    @FXML
    private TableColumn<Books, String> authorName;
    
    @FXML
    private void save() throws IOException {
        String title = txtTitle.getText();
        float price = Float.parseFloat(txtPrice.getText());
        String authorName = txtAuthor.getText();
        
        Books book = new Books(0, title, price, authorName);
        BooksEntity.getInstance().insert(book);
        
        clear();
        
        showData();
    }
    
    private void showData() {
        List<Books> dataList = BooksEntity.getInstance().findAll();
        
        bookView.getItems().clear();
        
        bookView.getItems().addAll(dataList);
    }
    
    @FXML
    private void delete() throws IOException {
        
    }
    
    @FXML
    private void search() throws IOException {
        
    }
    
    @FXML
    private void clear() throws IOException {
        txtTitle.setText("");
        txtPrice.setText("");
        txtAuthor.setText("");
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        id.setCellValueFactory(new PropertyValueFactory<Books, Integer>("id"));
        bookName.setCellValueFactory(new PropertyValueFactory<Books, String>("bookName"));
        price.setCellValueFactory(new PropertyValueFactory<Books, Float>("price"));
        authorName.setCellValueFactory(new PropertyValueFactory<Books, String>("authorName"));
        
        showData();
    }
}


#SecondaryController.java


package com.gokisoft.library;

import java.io.IOException;
import javafx.fxml.FXML;

public class SecondaryController {

    @FXML
    private void switchToPrimary() throws IOException {
        App.setRoot("library");
    }
}


#BaseEntity.java


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.models;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 * @param <T>
 */
public abstract class BaseEntity<T> {
    final String HOST = "jdbc:mysql://localhost:3308/library";
    final String USERNAME = "root";
    final String PASSWORD = "";
    
    Connection con = null;
    PreparedStatement statement = null;

    public void openConnection() {
        try {
            //KET NOI CSDL
            //B1. Tao ket noi toi CSDL
            con = DriverManager.getConnection(HOST, USERNAME, PASSWORD);
        } catch (SQLException ex) {
            Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void closeConnection() {
        //B3. Dong ket noi toi CSDL
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(BaseEntity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public abstract List<T> findAll();
    public abstract void insert(T item);
    public abstract void update(T item);
    public abstract void delete(T item);
    public abstract T findById(T item);
}


#Books.java


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.models;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class Books {
    private int id;
    private String bookName;
    private float price;
    private String authorName;

    public Books() {
    }

    public Books(int id) {
        this.id = id;
    }
    
    public Books(int id, String bookName, float price, String authorName) {
        this.id = id;
        this.bookName = bookName;
        this.price = price;
        this.authorName = authorName;
    }

    public Books(ResultSet resultSet) {
        try {
            this.id = resultSet.getInt("id");
            this.bookName = resultSet.getString("book_name");
            this.price = resultSet.getFloat("price");
            this.authorName = resultSet.getString("author_name");
        } catch (SQLException ex) {
            Logger.getLogger(Books.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    @Override
    public String toString() {
        return "id=" + id + ", bookName=" + bookName + ", price=" + price + ", authorName=" + authorName;
    }

    public void display() {
        System.out.println(this);
    }

    public void input() {
        Scanner scan = new Scanner(System.in);

        System.out.println("Nhap sach: ");
        bookName = scan.nextLine();
        System.out.println("Nhap gia: ");
        price = Float.parseFloat(scan.nextLine());
        System.out.println("Nhap ten tac gia: ");
        authorName = scan.nextLine();
    }
}


#BooksEntity.java


/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.models;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author teacher
 */
public class BooksEntity extends BaseEntity<Books>{
    private static BooksEntity instance = null;
    
    private BooksEntity() {
    }
    
    public synchronized static BooksEntity getInstance() {
        if(instance == null) {
            instance = new BooksEntity();
        }
        
        return instance;
    }

    @Override
    public List<Books> findAll() {
        List<Books> dataList = new ArrayList<>();
        
        openConnection();
        
        String sql = "select * from books";
        try {
            statement = con.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Books book = new Books(resultSet);
                dataList.add(book);
            }
        } catch (SQLException ex) {
            Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
        
        return dataList;
    }

    @Override
    public void insert(Books item) {
        openConnection();
        
        String sql = "insert into books(book_name, price, author_name) values (?, ?, ?)";
        try {
            statement = con.prepareStatement(sql);
            statement.setString(1, item.getBookName());
            statement.setFloat(2, item.getPrice());
            statement.setString(3, item.getAuthorName());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }

    @Override
    public void update(Books item) {
        openConnection();
        
        String sql = "update books set book_name=?,price=?,author_name=? where id=?";
        try {
            statement = con.prepareStatement(sql);
            statement.setString(1, item.getBookName());
            statement.setFloat(2, item.getPrice());
            statement.setString(3, item.getAuthorName());
            statement.setInt(4, item.getId());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }

    @Override
    public void delete(Books item) {
        openConnection();
        
        String sql = "delete from books where id=?";
        try {
            statement = con.prepareStatement(sql);
            statement.setInt(1, item.getId());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
    }

    @Override
    public Books findById(Books item) {
        Books itemFind = null;
        
        openConnection();
        
        String sql = "select * from books where id = ?";
        try {
            statement = con.prepareStatement(sql);
            statement.setInt(1, item.getId());
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                itemFind = new Books(resultSet);
                break;
            }
        } catch (SQLException ex) {
            Logger.getLogger(BooksEntity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        closeConnection();
        
        return itemFind;
    }
}


#module-info.java


module com.gokisoft.library {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.sql;

    opens com.gokisoft.library to javafx.fxml;
    exports com.gokisoft.library;
    exports com.gokisoft.models;
}


#library.fxml


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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>

<VBox alignment="TOP_CENTER" prefHeight="459.0" prefWidth="654.0" spacing="20.0" style="-fx-background-color: #cafcf4;" stylesheets="@style.css" xmlns="http://javafx.com/javafx/22" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.gokisoft.library.LibraryController">
   <padding>
      <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
   </padding>
   <children>
      <Pane prefHeight="140.0" prefWidth="614.0" styleClass="div_input">
         <children>
            <Label layoutX="14.0" layoutY="14.0" text="Ten Sach:" />
            <TextField fx:id="txtTitle" layoutX="97.0" layoutY="10.0" prefHeight="25.0" prefWidth="294.0" />
            <Label layoutX="14.0" layoutY="54.0" text="Gia:" />
            <TextField fx:id="txtPrice" layoutX="97.0" layoutY="50.0" prefHeight="25.0" prefWidth="294.0" />
            <Label layoutX="14.0" layoutY="92.0" text="Tac Gia:" />
            <TextField fx:id="txtAuthor" layoutX="97.0" layoutY="88.0" prefHeight="25.0" prefWidth="294.0" />
            <Button fx:id="btnSave" layoutX="416.0" layoutY="10.0" mnemonicParsing="false" onAction="#save" prefHeight="25.0" prefWidth="83.0" text="Luu" />
            <Button fx:id="btnDelete" layoutX="517.0" layoutY="10.0" mnemonicParsing="false" onAction="#delete" prefHeight="25.0" prefWidth="83.0" text="Xoa" />
            <Button fx:id="btnSearch" layoutX="416.0" layoutY="50.0" mnemonicParsing="false" onAction="#search" prefHeight="25.0" prefWidth="183.0" text="Tim Kiem" />
            <Button fx:id="btnClear" layoutX="416.0" layoutY="88.0" mnemonicParsing="false" onAction="#clear" prefHeight="25.0" prefWidth="183.0" text="Xoa Form" />
         </children></Pane>
      <TableView fx:id="bookView" prefHeight="282.0" prefWidth="614.0">
        <columns>
          <TableColumn prefWidth="75.0" text="STT" fx:id="id"/>
          <TableColumn prefWidth="267.0" text="Ten Sach" fx:id="bookName"/>
          <TableColumn minWidth="0.0" prefWidth="104.0" text="Gia" fx:id="price"/>
          <TableColumn prefWidth="167.0" text="Tac Gia" fx:id="authorName"/>
        </columns>
      </TableView>
   </children>
</VBox>


#secondary.fxml


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

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>

<VBox alignment="CENTER" spacing="20.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.gokisoft.library.SecondaryController">
    <children>
        <Label text="Secondary View" />
        <Button fx:id="secondaryButton" text="Switch to Primary View" onAction="#switchToPrimary" />
    </children>
    <padding>
        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
    </padding>
</VBox>


#style.css


.div_input {
    -fx-background-color: #c0effc;
}


Tags:



Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó