The book management system of Java practice (swing version) -- the interface and function implementation of book category adding

Posted by drepster on Sat, 01 Feb 2020 15:21:05 +0100

In the previous section, the creation of the main interface is completed. In this section, the function of adding book categories will be realized. The BookTypeAddPanel.java class file has been successfully created in the previous section, so you can write code directly in the file.

Since the database is used from this section, you need to import the jar package of the linked database, and the database and table have been created. You only need to execute the SQL statement in DB ﹣ booksystem.sql.

Note when using MySQL:

When the database is ready, you need to create the following classes:

The contents of each class are as follows:

BookTypeBean.java

package bookManageSystem.bean;
​
public class BookTypeBean {
    private int bookTypeId;
    private String bookTypeName;
    private String bookTypeDescription;
​
    public BookTypeBean() {
    }
​
    public BookTypeBean(int bookTypeId, String bookTypeName, String bookTypeDescription) {
        this.bookTypeId = bookTypeId;
        this.bookTypeName = bookTypeName;
        this.bookTypeDescription = bookTypeDescription;
    }
​
    public int getBookTypeId() {
        return bookTypeId;
    }
​
    public void setBookTypeId(int bookTypeId) {
        this.bookTypeId = bookTypeId;
    }
​
    public String getBookTypeName() {
        return bookTypeName;
    }
​
    public void setBookTypeName(String bookTypeName) {
        this.bookTypeName = bookTypeName;
    }
​
    public String getBookTypeDescription() {
        return bookTypeDescription;
    }
​
    public void setBookTypeDescription(String bookTypeDescription) {
        this.bookTypeDescription = bookTypeDescription;
    }
}

The properties of entity classes are created according to the column fields of the corresponding tables in the database.

BookTypeDao.java

package bookManageSystem.dao;
​
import java.sql.Connection;
import java.sql.Statement;
​
public class BookTypeDao {
​
    /**
     * Operation result: add, delete and modify the database according to the SQL statement
     *
     * @param sql SQL Sentence
     * @return boolean If the operation database succeeds, return true, otherwise return false
     */
    public boolean dataChange(String sql) {
        Connection conn = null;
        Statement stmt = null;
        try {
            //Get data connections
            new JDBCUtils();
            conn = JDBCUtils.getConnection();
            //Get Statement object
            stmt = conn.createStatement();
            //Send SQL statement and return the number of affected rows
            int num = stmt.executeUpdate(sql);
            // Judge whether the operation is successful according to the number of affected lines
            if (num > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(stmt, conn);
        }
        return false;
    }
}

JDBCUtils.java

package bookManageSystem.dao;
​
import java.sql.*;
​
/**
 * Connect JDBC class
 */
public class JDBCUtils {
​
    /**
     * Load driver and establish database connection
     *
     * @return Back to database connection
     * @throws SQLException           Throw SQLException
     * @throws ClassNotFoundException Throw ClassNotFoundException
     */
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        // Set database driver
        Class.forName("com.mysql.jdbc.Driver");
        // Database link URL and database name
        String url = "jdbc:mysql://localhost:3306/db_bookSystem";
        // Login account name
        String username = "root";
        // Login account password
        String password = "admin";
        // Create connection
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }
​
    /**
     * Close database connection and release resources
     *
     * @param stmt Statement object
     * @param conn Connection object
     */
    public static void release(Statement stmt, Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt = null;
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
​
    /**
     * Close database connection and release resources
     *
     * @param rs   ResultSet object
     * @param stmt Statement object
     * @param conn Connection object
     */
    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }
        release(stmt, conn);
    }
​
}

Methods related to database tables will be used later.

Open BookTypeAddPanel.java, and change the content into the following code:

package bookManageSystem.view;
​
import bookManageSystem.dao.BookTypeDao;
import bookManageSystem.tools.ComponentTools;
​
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
​
public class BookTypeAddPanel extends JPanel implements ActionListener {
    private ComponentTools componentTools = new ComponentTools();
​
    private Box totalVBox, funcationBox, typeNameBox, typeDescriptionBox, buttonBox;
    private JLabel typeNameLabel, bookTypeAddFuncationLabel, typeDescriptionLabel;
    private JTextArea typeDescriptionTextArea;
    private JTextField typeNameTextField;
    private JButton addButton, resetButton;
​
​
    BookTypeAddPanel() {
        // Add panel add control for book type
        this.add(this.createBookTypeAddBox());
        // Set icon for button
        componentTools.setIcons(new JButton[]{addButton, resetButton}, new String[]{"src/bookManageSystem/images/add.png", "src/bookManageSystem/images/reset.png"});
        // Register event listeners for buttons
​
    }
​
    /**
     * Control content of book type add panel
     *
     * @return Return to a Box
     */
    private Box createBookTypeAddBox() {
        // Create a vertical container box
        totalVBox = Box.createVerticalBox();
​
        // Create a horizontal container box
        funcationBox = Box.createHorizontalBox();
        bookTypeAddFuncationLabel = new JLabel("Book category adding function");
        bookTypeAddFuncationLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 30));
        funcationBox.add(bookTypeAddFuncationLabel);
        totalVBox.add(funcationBox);
        totalVBox.add(Box.createVerticalStrut(60));
​
        typeNameBox = Box.createHorizontalBox();
        typeNameLabel = new JLabel("Book category name:");
        typeNameTextField = new JTextField(20);
        typeNameBox.add(typeNameLabel);
        typeNameBox.add(Box.createHorizontalStrut(50));
        typeNameBox.add(typeNameTextField);
        totalVBox.add(typeNameBox);
        totalVBox.add(Box.createVerticalStrut(60));
​
        typeDescriptionBox = Box.createHorizontalBox();
        typeDescriptionLabel = new JLabel("Description of book category:");
        typeDescriptionTextArea = new JTextArea(10, 20);
        typeDescriptionTextArea.setLineWrap(true);
        typeDescriptionBox.add(typeDescriptionLabel);
        typeDescriptionBox.add(Box.createHorizontalStrut(50));
        typeDescriptionBox.add(typeDescriptionTextArea);
        totalVBox.add(typeDescriptionBox);
        totalVBox.add(Box.createVerticalStrut(60));
​
        buttonBox = Box.createHorizontalBox();
        addButton = new JButton("Add to");
        resetButton = new JButton("Reset");
        buttonBox.add(addButton);
        buttonBox.add(Box.createHorizontalStrut(80));
        buttonBox.add(resetButton);
        totalVBox.add(buttonBox);
​
        return totalVBox;
    }
​
    @Override
    public void actionPerformed(ActionEvent e) {
​
    }
}

Then run the program. After logging in successfully, click the "add book category" menu item under "book category management", and the following interface appears:

Clicking the "add" and "reset" buttons will not have any reaction, because there are no events registered for them here. There are several ways to register events for the buttons, here is just one of them.

First, add the following code in the BookTypeAddPanel() constructor method:

// Register event listeners for buttons
addButton.addActionListener(this);
resetButton.addActionListener(this);

The specific location is shown in the figure:

Then it implements the actionPerformed method. First, it implements the function of adding buttons.

Add the following code in the actionPerformed method:

        // Add event handling for button
        if (e.getSource() == addButton) {
            // Get book classification name
            String bookTypeName = typeNameTextField.getText();
            // Get book classification description
            String bookTypeDescription = typeDescriptionTextArea.getText();
            // Assembling SQL statements
            String sql =
                    "insert into tb_bookType (btName, btDescription) values ('" + bookTypeName + "','" + bookTypeDescription + "');";
            // Execute method insert a Book
            boolean isOK = new BookTypeDao().dataChange(sql);
            // Judge whether the operation is successful and make corresponding treatment
            if (isOK) {
                JOptionPane.showMessageDialog(null, "Added successfully!");
                componentTools.reset(typeNameTextField, typeDescriptionTextArea);
            } else {
                JOptionPane.showMessageDialog(null, "Failed to add!");
            }
        }

The above code deals with the event of the "add" button. Next, run the program again and log in successfully, then switch to the book category add interface and click the "add" button. The following conditions will appear:

Failed to add the record, and the console reported an error. The error log is as shown in the figure. After analyzing the log, it can be concluded that the class com.mysql.jdbc.Driver has not been found. In fact, the problem is that the jar package under the file folder has not been added.

In the future, we will encounter ClassNotFoundException, an exception that does not find a class. Most of the exceptions are not packed.

Then the next step is to add a third party package for this project.

Open Project Structure

Then select the Libraries tab

And find the jar package

Successfully added jar package

Similarly, other projects can add third-party jar packages in this way.

Run the project again and click the "add" button

This time, you can view the added record in the database:

The next step is to realize the reset function, which is to clear the text box and text field in the interface. The code is added in the actionPerformed method as follows:

        // Event handling of reset button
        if (e.getSource() == resetButton) {
            // That is, clear the contents of the input box
            componentTools.reset(typeNameTextField, typeDescriptionTextArea);
        }

You can run project query effects.

This section is finished. The next section will show how to realize the function of maintaining book category.

 

You can search the WeChat public number [Java instance program] or scan the underlying two-dimensional code to pay more attention to the public number.

Note: in the background of public address reply [20200201] can get the source code of this section.

 

410 original articles published, 43 praised, 100000 visitors+
Private letter follow

Topics: Database SQL Java MySQL