combate del sistema de facturación de Java ama de llaves (10) - cambiar cuentas de interfaz y funciones para lograr

Esta cláusula general

Esta sección será modificado los registros contables.

 

interfaz de creación

FXML acumulación modificar el archivo, el archivo se crea alterAccountFrame.fxml En paquete de vista, use la escena Generador de componentes de la interfaz de diseño, propiedades y eventos de cada referencia método de control para el siguiente código:

<?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.AlterAccountFrameController">
    <children>
        <VBox alignment="CENTER" focusTraversable="true" layoutX="147.0" layoutY="10.0" prefHeight="400.0"
              prefWidth="326.0" spacing="20.0">
            <children>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="序号:"/>
                        <TextField fx:id="idTextField" prefWidth="240.0" promptText="请填入记录的序号:"/>
                    </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" disable="true" mnemonicParsing="false"
                                             onAction="#outputRadioButtonEvent" text="支出">
                                    <toggleGroup>
                                        <ToggleGroup fx:id="group"/>
                                    </toggleGroup>
                                </RadioButton>
                                <RadioButton fx:id="inputRadioButton" disable="true" 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" disable="true" prefHeight="30.0" prefWidth="240.0"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0">
                    <children>
                        <Label text="分类:"/>
                        <ComboBox fx:id="classificationComboBox" disable="true" 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" disable="true" 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="datePickerText" disable="true" prefHeight="30.0" prefWidth="240.0"/>
                    </children>
                </HBox>
                <HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0" spacing="50.0">
                    <children>
                        <Button fx:id="checkButton" mnemonicParsing="false" onAction="#checkButtonEvent" text="查询"/>
                        <Button fx:id="alterButton" disable="true" mnemonicParsing="false" onAction="#alterButtonEvent"
                                text="更改"/>
                    </children>
                </HBox>
            </children>
            <opaqueInsets>
                <Insets/>
            </opaqueInsets>
            <padding>
                <Insets bottom="20.0"/>
            </padding>
        </VBox>
    </children>
</AnchorPane>

A continuación, crear clase controlador AlterAccountFrameController.java correspondiente en el controlador de paquetes, el controlador de la copia de código de objeto de clase base del conjunto en la clase Escena Constructor:

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.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
​
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
​
/**
 * 更改账目界面控制器
 *
 * @author lck100
 */
public class AlterAccountFrameController {
    private PublicTools publicTools = new PublicTools();
​
    @FXML
    private String selectedCoboboxItem = null;
​
    @FXML
    private String selectedRadioButton = null;
​
    @FXML
    private TextField idTextField;
​
    @FXML
    private RadioButton outputRadioButton;
​
    @FXML
    private Button alterButton;
​
    @FXML
    private TextField moneyTextField;
​
    @FXML
    private DatePicker datePickerText;
​
    @FXML
    private RadioButton inputRadioButton;
​
    @FXML
    private TextArea memoTextArea;
​
    @FXML
    private ComboBox<?> classificationComboBox;
​
    /**
     * “支出”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void outputRadioButtonEvent(ActionEvent actionEvent) {
        
    }
​
    /**
     * “收入”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void inputRadioButtonEvent(ActionEvent actionEvent) {
        
    }
​
    /**
     * ”分类“下拉列表框的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void classificationComboBoxEvent(ActionEvent actionEvent) {
        
    }
​
    /**
     * ”查询“按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void checkButtonEvent(ActionEvent actionEvent) {
        
    }
​
    /**
     * ”更改“按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void alterButtonEvent(ActionEvent actionEvent) {
        
    }
}

A continuación, crear un método en el archivo cargado MainApp.java FXML:

    /**
     * 操作结果:更改账目界面
     */
    public Scene initAlterFrame() {
        try {
​
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/alterAccountFrame.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
​
            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.showAndWait();
            return scene;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Por último, para modificar los elementos de menú registrados en el evento MainPageController.java, a saber:

    /**
     * ”修改“菜单项的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void alterMenuItemEvent(ActionEvent actionEvent) {
        // 刷新数据
        initialize();
        // 调用修改界面控制器
        mainApp.initAlterFrame();
    }

Ejecutar el programa, la interfaz es la siguiente:

 

 

Realizar la función

Implementar la función de modificación, por primera vez en algunos, como botones de radio en la interfaz, el método de evento componente de lista de caja desplegable, consulte el siguiente código, que añaden funcionalidad en dicha sección, así que no hay explicación.

    public void initialize() {
        idTextField.setText("");
        inputRadioButton.setSelected(false);
        inputRadioButton.setDisable(true);
        outputRadioButton.setSelected(false);
        outputRadioButton.setDisable(true);
        moneyTextField.setText("");
        moneyTextField.setDisable(true);
        classificationComboBox.getItems().clear();
        classificationComboBox.setDisable(true);
        memoTextArea.setText("");
        memoTextArea.setDisable(true);
        datePickerText.getEditor().setText("");
        datePickerText.setDisable(true);
        alterButton.setDisable(true);
    }
​
    /**
     * “支出”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    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();
    }
​
    /**
     * “收入”单选按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    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();
    }
​
    /**
     * ”分类“下拉列表框的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void classificationComboBoxEvent(ActionEvent actionEvent) {
        //只处理选中的状态
        selectedCoboboxItem = (String) classificationComboBox.getSelectionModel().selectedItemProperty().getValue();
    }

Consulta función del botón de adquisición número es entrada por un usuario, y de consulta los datos obtenidos de la base de datos se muestra en cada llenado de montaje, la investigación con la función de eliminación sección es la misma, la única diferencia es que los datos actuales de cada sección pantallas de control, incluyendo cuadros desplegables de lista, botones de radio, y la información que acaba de borrar esa sección que ha de suprimirse aparece en una ficha.

Así código del botón de consulta de control de eventos es la siguiente:

    /**
     * ”查询“按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void checkButtonEvent(ActionEvent actionEvent) {
        // 实例化RecordDao
        RecordDao recordDao = new RecordDao();
        // 实例化ClassificationDao
        ClassificationDao classificationDao = new ClassificationDao();
​
        String id = idTextField.getText();
        // 判断用户是否输入要查询的序号
        if (id == null || id.equals("")) {
            SimpleTools.informationDialog(Alert.AlertType.WARNING, "警告", "警告", "要查询的ID不能为空!");
        } else {
            // 使用正则表达式判断用户输入是否是数字而不是字符串
            boolean bb = Pattern.compile("^[-\\+]?[\\d]*$").matcher(id).matches();
            if (bb) {
                Record checkedRecord = recordDao.selectRecordByIdAndUserId(Integer.parseInt(id), Session.getUser().getUserId());
                if (checkedRecord.getRecordType() == null && checkedRecord.getRecordClassification() == null) {
                    SimpleTools.informationDialog(Alert.AlertType.WARNING, "警告", "警告", "该项不存在,请重新输出序号!");
                    // 重置数据填充
//                    initialize();
                } else {
                    // 使界面组件可编辑
                    inputRadioButton.setDisable(false);
                    outputRadioButton.setDisable(false);
                    moneyTextField.setDisable(false);
                    classificationComboBox.setDisable(false);
                    memoTextArea.setDisable(false);
                    datePickerText.setDisable(false);
                    alterButton.setDisable(false);
​
                    // 设置界面的值
                    if (checkedRecord.getRecordType().equals("支出")) {
                        //设置类型
                        outputRadioButton.setSelected(true);
                    } else {
                        inputRadioButton.setSelected(true);
                    }
​
                    // 如果支出单选按钮被选中
                    if (outputRadioButton.isSelected()) {
                        // 查询支出分类所在的名称
                        List<Classification> classificationList = classificationDao.selectByType("支出");
                        // 实例化一个一维数组
                        String[] classificationNames = new String[classificationList.size()];
                        // 将查询得到的分类名称装到一维数组中
                        for (int i = 0; i < classificationList.size(); i++) {
                            classificationNames[i] = classificationList.get(i).getcName();
                        }
                        // 重新为下拉列表框赋予选项
                        classificationComboBox.setItems(FXCollections.observableArrayList((List) Arrays.asList(classificationNames)));
                    }
                    // 如果收入单选按钮被选中
                    if (inputRadioButton.isSelected()) {
                        // 查询支出分类所在的名称
                        List<Classification> classificationList = classificationDao.selectByType("收入");
                        // 实例化一个一维数组
                        String[] classificationNames = new String[classificationList.size()];
                        // 将查询得到的分类名称装到一维数组中
                        for (int i = 0; i < classificationList.size(); i++) {
                            classificationNames[i] = classificationList.get(i).getcName();
                        }
                        // 重新为下拉列表框赋予选项
                        classificationComboBox.setItems(FXCollections.observableArrayList((List) Arrays.asList(classificationNames)));
                    }
​
                    //设置金额
                    moneyTextField.setText(String.valueOf(checkedRecord.getRecordMoney()));
​
                    // 设置分类
                    String str = checkedRecord.getRecordClassification();
                    int index = 0;
                    if (checkedRecord.getRecordType().equals("支出")) {
                        List outputList = FXCollections.observableArrayList((List) classificationDao.selectByType("收入"));
                        for (int i = 0; i < outputList.size(); i++) {
                            if (str.equals(outputList.get(i))) {
                                index = i;
                            }
                        }
                        classificationComboBox.getSelectionModel().select(index);
                    }
                    if (checkedRecord.getRecordType().equals("收入")) {
                        List inputList = FXCollections.observableArrayList((List) classificationDao.selectByType("收入"));
                        for (int i = 0; i < inputList.size(); i++) {
                            if (str.equals(inputList.get(i))) {
                                index = i;
                            }
                        }
                        classificationComboBox.getSelectionModel().select(index);
                    }
                    //设置备注
                    memoTextArea.setText(checkedRecord.getRecordMemo());
                    //设置日期
                    datePickerText.setValue(LocalDate.parse(checkedRecord.getRecordDate()));
                }
            } else {
                SimpleTools.informationDialog(Alert.AlertType.WARNING, "警告", "警告", "序号应该为数字而不是字符串!");
            }
​
        }
    }

Mientras que muchos buscan en el código anterior, de hecho, la esencia es conseguir que los datos sean modificados, y luego se muestran en los controles de la interfaz, la mayor parte del código va a resolver todos los datos de la información de control.

Consulta de las pruebas de función son los siguientes:

El siguiente paso es para cambiar la función de la adquisición de datos a ser modificado y desde la interfaz, se puede actualizar la base de datos.

Así que cambiar el código de evento de botón de la siguiente manera:

    /**
     * ”更改“按钮的事件监听器
     *
     * @param actionEvent 事件
     */
    @FXML
    public void alterButtonEvent(ActionEvent actionEvent) {
        // 序号
        int id = Integer.parseInt(idTextField.getText());
        //类型
        String type = "";
        if (inputRadioButton.isSelected()) {
            type = inputRadioButton.getText();
        } else if (outputRadioButton.isSelected()) {
            type = outputRadioButton.getText();
        }
        // 金额,把从文本框得到的string类型数据转换为float类型
        float money = Float.parseFloat(moneyTextField.getText());
        // 分类
        String classification = classificationComboBox.getSelectionModel().getSelectedItem().toString();
        // 备注
        String memo = memoTextArea.getText();
        // 日期
        String date = datePickerText.getValue().toString();
        // 将用户修改的数据封装到实体类中
        Record record = new Record(Session.getUser().getUserId(), id, type, money, classification, memo, date);
        // 实例化RecordDao对象
        RecordDao recordDao = new RecordDao();
        // 执行修改操作
        boolean b = recordDao.updateRecord(record);
        // 对修改结果进行判断
        if (b) {
            SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "信息", "修改账目成功!");
        } else {
            SimpleTools.informationDialog(Alert.AlertType.ERROR, "提示", "错误", "修改账目失败!");
        }
    }

Este código de la lógica está escrito, para ejecutar el programa, la prueba de funcionamiento:

exitosa:

 

 

número de micro-canales públicos de búsqueda [ programa de ejemplo de Java ] o escanear el código Fanger Wei para obtener más atención del público.

Nota: respuesta a un segundo plano en el No. pública [ 20200328 ] se puede obtener el código fuente de este capítulo.

 

Publicados 500 artículos originales · ganado elogios 77 · vistas 160 000 +

Supongo que te gusta

Origin blog.csdn.net/cnds123321/article/details/104281194
Recomendado
Clasificación