Java combat the housekeeper billing system (8) - Add Accounts interface and functions to achieve

This clause Overview

 

This section will be added in the accounting records.

 

Preparatory

Add achieved records in this section will be used in the query classification of information, so creating ClassificationDao.java dao class in the package, as follows:

package AccountSystem.dao;
​
import AccountSystem.bean.Classification;
​
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
​
public class ClassificationDao {
​
    /**
     * 通过收入或支出类型获取所有的分类信息
     *
     * @param classificationType 收入或支出分类
     * @return 返回得到的分类信息
     */
    public List<Classification> selectByType(String classificationType) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List<Classification> classificationList = new ArrayList<Classification>();
        try {
            //获得数据的连接
            conn = JDBCUtils.getConnection();
            //获得Statement对象
            stmt = conn.createStatement();
            // 拼接SQL语句
            String sql = "select * from tb_classification where cType='" + classificationType + "';";
            //发送SQL语句
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Classification classification = new Classification();
                classification.setcId(rs.getInt(1));
                classification.setcName(rs.getString(2));
                classification.setcType(rs.getString(3));
                classificationList.add(classification);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, stmt, conn);
        }
        return classificationList;
    }
}

 

Implement interface

Must first complete a feature added in JavaFX, first create FXML view files, then create the associated controller class Controller, then the method to load FXML view files created in MainApp, and finally call in an event .

In view package addAccountFrame.fxml create files, and use the Scene Builder interface design, properties, and events of each control method refer to the following codes:

<?xml version="1.0" encoding="UTF-8"?>
​
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="AccountSystem.controller.AddAccountFrameController">
    <children>
        <VBox alignment="CENTER" focusTraversable="true" layoutX="137.0" prefHeight="400.0" prefWidth="326.0"
              spacing="20.0">
            <children>
                <HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label fx:id="descriptionLabel" text="添加"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="类型:"/>
                        <HBox alignment="CENTER_LEFT" prefHeight="30.0" prefWidth="240.0" spacing="50.0">
                            <children>
                                <RadioButton fx:id="outputRadioButton" mnemonicParsing="false"
                                             onAction="#outputRadioButtonEvent" text="支出">
                                    <toggleGroup>
                                        <ToggleGroup fx:id="group"/>
                                    </toggleGroup>
                                </RadioButton>
                                <RadioButton fx:id="inputRadioButton" mnemonicParsing="false"
                                             onAction="#inputRadioButtonEvent" text="收入" toggleGroup="$group"/>
                            </children>
                        </HBox>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="金额:"/>
                        <TextField fx:id="moneyTextField" prefHeight="30.0" prefWidth="240.0" promptText="请填入金额:"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="分类:"/>
                        <ComboBox fx:id="classificationComboBox" onAction="#classificationComboBoxEvent"
                                  prefHeight="30.0" prefWidth="240.0" promptText="请选择分类:"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="备注:"/>
                        <TextArea fx:id="memoTextArea" prefHeight="200.0" prefWidth="240.0" promptText="请填入备注:"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="日期:"/>
                        <DatePicker fx:id="datePickerTextField" prefHeight="30.0" prefWidth="240.0"
                                    promptText="请选择日期:"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Button fx:id="addButton" mnemonicParsing="false" onAction="#addButtonEvent" text="添加"/>
                    </children>
                </HBox>
            </children>
            <opaqueInsets>
                <Insets/>
            </opaqueInsets>
            <padding>
                <Insets bottom="20.0"/>
            </padding>
        </VBox>
    </children>
</AnchorPane>

Then create AddAccountFrameController.java class in the controller package and copied from the Scene Builder objects and events in the control method to the class:

package AccountSystem.controller;
​
import AccountSystem.bean.Classification;
import AccountSystem.bean.Record;
import AccountSystem.bean.Session;
import AccountSystem.dao.ClassificationDao;
import AccountSystem.dao.RecordDao;
import AccountSystem.tools.PublicTools;
import AccountSystem.tools.SimpleTools;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
​
import java.util.List;
​
/**
 * 添加账目界面控制器
 *
 * @author lck100
 */
public class AddAccountFrameController {
    private PublicTools publicTools = new PublicTools();
​
    @FXML
    private String selectedRadioButton = null;
​
    @FXML
    private String selectedCoboboxItem = null;
​
    @FXML
    private Label descriptionLabel;
​
    @FXML
    private RadioButton outputRadioButton;
​
    @FXML
    private DatePicker datePickerTextField;
​
    @FXML
    private TextField moneyTextField;
​
    @FXML
    private RadioButton inputRadioButton;
​
    @FXML
    private TextArea memoTextArea;
​
    @FXML
    private ComboBox<?> classificationComboBox;
​
    /**
     * “添加”按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void addButtonEvent(ActionEvent actionEvent) {
      
    }
​
    /**
     * “支出”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    public void outputRadioButtonEvent(ActionEvent actionEvent) {
       
    }
​
    /**
     * “收入”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    public void inputRadioButtonEvent(ActionEvent actionEvent) {
      
    }
​
    /**
     * ”分类“下拉列表框的事件监听器
     *
     * @param actionEvent 事件
     */
    public void classificationComboBoxEvent(ActionEvent actionEvent) {
       
    }
}

Code Description:

You can see there are four event listener method above, add a button event handler is well understood that when the record after the user enters information into a database table, but the other three methods may not understand why they want to listen. The "expenditure" and "income" radio button listeners are similar, because "spending" There are many different classifications, and these classifications are displayed in the drop-down list box, the same classification of all "income" is also displayed in the drop-down list box, it is impossible to classify the income and expenditure are shown together, the two radio buttons above setting would be meaningless, there will be no division of income and expenditures.

So when the user selects the "income" radio button, all income category name will be filled in the drop-down list box; When the user selects "spending" radio button, it will all spending category name to fill the following drop-down list box, allowing the user to select category separately.

Drop-down list box dynamically monitor events is to get the category name selected by the user.

The following changes will demonstrate listening radio buttons:

Click "Add" to add pop-up menu interface as follows (this time two radio buttons are not selected, so there is no drop-down list box value):

Select the "expenditure" radio button, the following classification of all "expenses" category name:

Select the "income" radio button, the following classification of all "income" category name:

And a controller interface view finished, followed by loading the interface FXML view, add the following method of loading addAccountFrame.fxml file MainApp.java:

    /**
     * 操作结果:添加账目界面
     */
    public Scene initAddFrame() {
        try {
            Parent page = FXMLLoader.load(getClass().getResource("view/addAccountFrame.fxml"));
​
            Stage mainFrameStage = new Stage();
            mainFrameStage.setTitle("添加账目");
            mainFrameStage.setResizable(true);
            mainFrameStage.setAlwaysOnTop(false);
            mainFrameStage.initModality(Modality.APPLICATION_MODAL);
            mainFrameStage.initOwner(primaryStage);
            Scene scene = new Scene(page);
            mainFrameStage.setScene(scene);
​
            mainFrameStage.show();
            return scene;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Then add a menu item is invoked in the event MainPageController.java:

    /**
     * ”添加“菜单项的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void addMenuItemEvent(ActionEvent actionEvent) {
        // 刷新界面数据
        initialize();
        // 调用添加账目界面
        mainApp.initAddFrame();
    }

Run the project you can see the added interface, but there is no event handler, only interface.

 

Add Features

AddAccountFrameController add functionality implemented in the addButtonEvent () method, as follows:

        // 类型
        String type = selectedRadioButton;
        // 金额,把从文本框得到的string类型数据转换为float类型
        float money = Float.parseFloat(moneyTextField.getText());
        // 分类
        String classification = selectedCoboboxItem;
        // 备注
        String memo = memoTextArea.getText();
        // 日期
        String date = datePickerTextField.getValue().toString();
        // 将用户输入的数据封装到Record实体类中
        Record record = new Record(Session.getUser().getUserId(), type, money, classification, memo, date);
        // 实例化RecordDao对象
        RecordDao recordDao = new RecordDao();
        // 添加数据到数据库
        boolean b = recordDao.addRecord(record);
        // 对添加操作的结果进行判断处理
        if (b) {
            SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "信息", "添加账目成功!");
            // 清空用户选择
            outputRadioButton.setSelected(false);
            inputRadioButton.setSelected(false);
            moneyTextField.setText("");
            classificationComboBox.getItems().clear();
            memoTextArea.setText("");
            datePickerTextField.getEditor().setText("");
        } else {
            SimpleTools.informationDialog(Alert.AlertType.ERROR, "提示", "错误", "添加账目失败!");
        }

Code Description: acquiring information entered by the user, and then encapsulated Record entity class object, call addRecord RecordDao () in the add operation, and then add the results of the determination process.

Event Processing "spending" radio buttons are as follows:

    /**
     * “支出”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    public void outputRadioButtonEvent(ActionEvent actionEvent) {
        // 获取支出分类的所有信息
        List<Classification> classificationList = new ClassificationDao().selectByType("支出");
        // 实例化一个一维数组
        String[] classificationNames = new String[classificationList.size()];
        // 将查询得到的分类名称装到一维数组中
        for (int i = 0; i < classificationList.size(); i++) {
            classificationNames[i] = classificationList.get(i).getcName();
        }
        // 给下拉列表框添加选项
        publicTools.public_addComboBoxItems(classificationComboBox, classificationNames);
        // 获取单选按钮项
        selectedRadioButton = outputRadioButton.getText();
        // 设置descriptionLabel文本内容
        descriptionLabel.setText("添加" + outputRadioButton.getText());
    }

Definitions: By selectByType ClassificationDao class method to get all expenditure category name, and converts () into which a one-dimensional array, and then call public_addComboBoxItems () method of class PublicTools fill data, and supplies the selected radio button assign a value to a variable, and then use the "add" event handling.

Event Processing "income" radio button is as follows:

    /**
     * “收入”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    public void inputRadioButtonEvent(ActionEvent actionEvent) {
        // 获取收入分类的所有信息
        List<Classification> classificationList = new ClassificationDao().selectByType("收入");
        // 实例化一个一维数组
        String[] classificationNames = new String[classificationList.size()];
        // 将查询得到的分类名称装到一维数组中
        for (int i = 0; i < classificationList.size(); i++) {
            classificationNames[i] = classificationList.get(i).getcName();
        }
        // 给下拉列表框添加选项
        publicTools.public_addComboBoxItems(classificationComboBox, classificationNames);
        // 获取单选按钮项
        selectedRadioButton = inputRadioButton.getText();
        //设置descriptionLabel文本内容
        descriptionLabel.setText("添加" + inputRadioButton.getText());
    }

"Category" drop-down list box event handler as follows:

    /**
     * ”分类“下拉列表框的事件监听器
     *
     * @param actionEvent 事件
     */
    public void classificationComboBoxEvent(ActionEvent actionEvent) {
        //只处理选中的状态
        selectedCoboboxItem = (String) classificationComboBox.getSelectionModel().selectedItemProperty().getValue();
    }

All logic code completion, now is running the project, test function:

You can then view the added record of success in the main interface:

 

 

Searchable public micro-channel number [ Java example program ] or scan the Fanger Wei code number to get more public attention.

Note: Reply to [the public number background 20200324 ] can get the source code of this chapter.

 

Published 500 original articles · won praise 77 · views 160 000 +

Guess you like

Origin blog.csdn.net/cnds123321/article/details/104278434