Java 组合框选择和模型绑定

Java 组合框选择和模型绑定,java,mysql,javafx,combobox,model,Java,Mysql,Javafx,Combobox,Model,问题概述: 我有两种型号OrderModel和OrderStatusModel。OrderStatusModel项被放入一个组合框中,该组合框包含用户更新名为orderStatusId的Order表中外键字段的选项。初始化数据时,我希望能够从OrderModel中提取并检索当前的orderStatusId,然后设置组合框(包含所有用户选择)以匹配OrderModel中的orderStatusId(其中包含Order表中的FK)。当做出新选择时,组合框需要能够更新OrderModel。当从数据库获

问题概述:

我有两种型号
OrderModel
OrderStatusModel
OrderStatusModel
项被放入一个组合框中,该组合框包含用户更新名为
orderStatusId
Order
表中外键字段的选项。初始化数据时,我希望能够从
OrderModel
中提取并检索当前的
orderStatusId
,然后设置组合框(包含所有用户选择)以匹配
OrderModel
中的
orderStatusId
(其中包含
Order
表中的FK)。当做出新选择时,组合框需要能够更新
OrderModel
。当从数据库获取数据以填充
OrderModel
时,我会提取FK
orderStatusId
。从这一点开始,我使用case语句在
OrderStatusModel
中选择适当的项,并选择初始化选项。我知道这不是最好的方法,因为如果我要在后端数据库中为新类型的状态(例如:订单取消)添加新行,那么我需要去更新我的所有switch语句以允许该更改

示例代码

控制器

package test.pkg2;

import java.awt.Label;
import java.beans.Statement;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;

public class Test2Controller implements Initializable{

    @FXML
    private Label customerName;

    @FXML
    private Label orderNumber;

    @FXML
    private Label orderStatusId;

    @FXML
    private ComboBox<OrderStatusModel> orderStatusCmb;

    private ObservableList<OrderStatusModel> orderStatusModel;
    private ObservableList<OrderModel> orderModel;

    int statusId;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.orderStatusCmb.getSelectionModel().selectedItemProperty().addListener((obs, newValue, oldValue) ->{
            if(newValue != null && newValue != oldValue){
                this.orderStatusCmb.getSelectionModel().getSelectedItem().getOrderStatusId();
                //TODO UPDATE Order table with new orderStatusId from above code ^^^^^^
            }
        });
        populateOrderStatusCombobox();
        getCurrentOrder();
    }

    private void populateOrderStatusCombobox(){
        String SQL = "SELECT Status.statusId, Status.statusName \n" 
                     +"FROM Status;";

        orderStatusModel = FXCollections.observableArrayList();

        //Status table:
        // +-----------+-------------+------+-----+---------+
        // | Field     | Type        | Null | Key | Default |
        // +-----------+-------------+------+-----+---------+
        // | statusId  | int         | YES  | PK  | NULL    |       
        // | statusName| varchar(20) | YES  |     | NULL    |       
        // +-----------+-------------+------+-----+---------+

        //example data: statusId = 1 statusName = Order Taken
        //example data: statusId = 2 statusName = Order Processing
        //example data: statusId = 3 statusName = Shipped

        //Above items are populated into the combobox for selection
        try(Connection connection = DBConnection.getConnection()){
            PreparedStatement statement = connection.prepareStatement(SQL);
            ResultSet resultSet = statement.executeQuery();
            while(resultSet.next()){
                this.orderStatusModel.add(new OrderStatusModel(resultSet.getInt("statusId"),
                                                    resultSet.getString("statusName")));
            }
        } catch(SQLException e){

        }
        this.orderStatusCmb.setItems(orderStatusModel);
    }
    private void getCurrentOrder(){
        String SQL = "SELECT Order.orderNumber, Order.customerName, Order.orderStatusId \n"
                    +"FROM Order"
                    +"WHERE orderNumber = 123;";
        orderModel = FXCollections.observableArrayList();

        //Order table:
        // +--------------+-------------+------+-----+---------+
        // | Field        | Type        | Null | Key | Default |
        // +--------------+-------------+------+-----+---------+
        // | orderNumber  | int         | YES  | PK  | NULL    |       
        // | customerName | varchar(20) | YES  |     | NULL    |       
        // | orderStatusId| int         | YES  | FK  | NULL    |  
        // +--------------+-------------+------+-----+---------+

        //example data: orderNumber = 123
        //              customerName = SomeCompany
        //              orderStatusId = 1

        //I usually set the combobox here using the below method:
        try(Connection connection = DBConnection.getConnection()){
            PreparedStatement statement = connection.prepareStatement(SQL);
            ResultSet resultSet = statement.executeQuery();
            while(resultSet.next()){
                this.orderModel.add(new OrderModel(resultSet.getInt("orderNumber"),
                                                    resultSet.getString("customerName"),
                                                    resultSet.getInt("orderStatusId")));
                                                    statusId = resultSet.getInt("orderStatusId");
            }

            //HERE is where I initially set the orderStatus to match the orderModel
            //I am guessing I need some kind of binding here?
           switch(statusId){
               case 1: this.orderStatusCmb.getSelectionModel().select(0);
               break;
               case 2: this.orderStatusCmb.getSelectionModel().select(1);
               break;
               case 3: this.orderStatusCmb.getSelectionModel().select(3);
               break;
           }
        } catch(SQLException e){

        }
    }
}
OrderModel

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;


public class OrderStatusModel {
    private final IntegerProperty orderStatusId;
    private final StringProperty orderStatusName;

    public OrderStatusModel(int orderStatusId, String orderStatusName){
        this.orderStatusId = new SimpleIntegerProperty(orderStatusId);
        this.orderStatusName = new SimpleStringProperty(orderStatusName);
    }

    public IntegerProperty getOrderStatusId() {
        return orderStatusId;
    }

    public StringProperty getOrderStatusName() {
        return orderStatusName;
    }
}
package test.pkg2;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class OrderModel {

    private final IntegerProperty orderNumber;
    private final StringProperty customerName;
    private final IntegerProperty orderStatusId;

    public OrderModel(int orderNumber, String customerName, int orderStatusId){
        this.orderNumber = new SimpleIntegerProperty(orderNumber);
        this.customerName = new SimpleStringProperty(customerName);
        this.orderStatusId = new SimpleIntegerProperty(orderStatusId);
    }

    public IntegerProperty getOrderNumber() {
        return orderNumber;
    }

    public StringProperty getCustomerName() {
        return customerName;
    }

    public IntegerProperty getOrderStatusId() {
        return orderStatusId;
    }
}

您不需要使用任何显式绑定来实现选项和ID之间的链接。相反,通过OrderStatusModel对象支持combobox,该对象已经包含ID和友好字符串名称,然后将适当的StringConverter应用到combobox将实现combobox的良好显示。id->friendly name链接仍然保留在model类中,可以根据需要在后续数据库更新中反向使用

样本

此示例的作用是:

  • 将数据库交互提取到接口
  • 提供数据库接口的内存内实现示例(将其替换为执行实际数据库访问代码的实现)
  • 在一个单独的类中定义数据库访问,该类将其逻辑移出您的UI代码,以便您可以更轻松地独立开发、测试和交换其实现逻辑(这是非常可取的,即使对于一个小应用程序也是如此)
  • 用代码而不是FXML定义UI布局(最好使用FXML,但在代码中创建它只是为了让代码相对简短)
  • 将模型类上访问器的命名约定更新为xxxProperty(),而不是您使用的getXXX()。根据标准JavaFX命名约定,任何返回属性的内容都应该具有属性的名称后缀。getXXX()方法用于检索属性的实际值,而不是属性本身
  • 在OrderModel中,订单状态记录为ObjectProperty,这使得OrderModel更易于使用,因为它包含了所有相关的状态信息,而不需要连接和查询来获取其他信息。我知道它在数据库系统中不是这样表示的,但是让数据库接口类进行转换并返回所有相关信息通常是处理这种情况的更好方法
  • 使用组合框时,使用valueProperty而不是selectedItemProperty,因为valueProperty更直接地表示组合框的值(在这种情况下,用户总是从“选择”下拉列表中进行选择,并且不能对值部分进行文本编辑,但从概念上讲,仅使用值更直接一些)
  • 为组合框定义了一个StringConverter,它将OrderStatusModel值转换为友好的字符串名称,以便在组合框中显示
  • 为OrderStatusModel定义equals和hashcode,以便可以使用适当的匹配和复制逻辑(否则,它们可能不会像您期望的那样)将其与Java collections API进行适当的比较并插入到集合中
样本输出

ComboApp.java

背景

此答案大致基于JavaFX论坛帖子中的类似问题和答案,该帖子与ChoiceBox而非ComboBox相关:

但是,此答案将更新为直接使用组合框而不是选择框

无关建议

关于您发布的代码,有几个无关的建议:

  • 如果不重新引用异常、对异常采取行动或记录异常,就永远不要捕获异常。即使它只是发布在internet上的示例代码,也不要这样做
  • 您导入
    java.awt.Label
    ,然后尝试使用FXML注入它:这不对,您应该使用
    javafx.scene.control.Label
    。不要混合使用awt代码和javafx代码

您的问题是什么?您是否要求他人编写代码来替换“TODO”注释,并在其中编写“我猜我需要某种绑定?”?@jewelsea我会检查这些,看看这是否有效。我正试图找出我可以做什么来替代使用用例。我目前所做的最大问题是,如果我对数据库进行任何更改,我必须更改大量代码,这在我的理解中是不好的做法。在“我想我需要一些装订?"我认为将这两个模型绑定在一起的方法可能会起作用,因为我看到其他帖子做了一些类似的事情。谢谢你的帖子和建议。你的示例答案非常有用。谢谢你的深入解释。我看到了我可以改进的所有项目;添加多态性、正确的命名约定,更好使用OOP实践,但没有
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.util.Optional;

public class ComboApp extends Application {
    private Label orderNumber = new Label();
    private Label customerName = new Label();
    private ComboBox<OrderStatusModel> orderStatus = new ComboBox<>();

    private Database database = new InMemoryTestDatabase();

    @Override
    public void start(Stage stage) throws Exception {
        HBox layout = new HBox(
                10, 
                orderNumber, 
                customerName, 
                orderStatus
        );
        layout.setPadding(new Insets(10));
        layout.setAlignment(Pos.BASELINE_LEFT);

        populateOrderStatusCombobox();
        showOrder(123);
        updateOrderWhenStatusChanged();

        stage.setScene(new Scene(layout));
        stage.show();
    }

    private void updateOrderWhenStatusChanged() {
        orderStatus.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null && !newValue.equals(oldValue)) {
                database.updateOrder(
                        new OrderModel(
                                Integer.parseInt(orderNumber.getText()),
                                customerName.getText(),
                                orderStatus.getValue()
                        )
                );

                System.out.println(
                        "Updated order status of order "
                                + orderNumber.getText()
                                + " to "
                                + orderStatus.getValue()
                                    .orderStatusNameProperty()
                                    .getValue()
                );
            }
        });
    }

    private void populateOrderStatusCombobox(){
        orderStatus.setPlaceholder(new Label("None Selected"));
        orderStatus.getItems().setAll(database.listAllOrderStatuses());

        orderStatus.setConverter(new StringConverter<OrderStatusModel>() {
            @Override
            public String toString(OrderStatusModel orderStatusModel) {
                return orderStatusModel.orderStatusNameProperty().get();
            }

            @Override
            public OrderStatusModel fromString(String orderStatusName) {
                Optional<OrderStatusModel> result = database.findOrderStatusWithName(
                        orderStatusName
                );

                return result.orElse(null);
            }
        });
    }

    private void showOrder(int orderId){
        Optional<OrderModel> result = database.findOrderById(orderId);

        if (!result.isPresent()) {
            orderNumber.setText("");
            customerName.setText("");
            orderStatus.setValue(null);

            return;
        }

        OrderModel order = result.get();

        orderNumber.setText("" + order.orderNumberProperty().get());
        customerName.setText(order.customerNameProperty().get());
        orderStatus.setValue(order.orderStatusProperty().get());
    }

    public static void main(String[] args) {
        launch(args);
    }
}
import java.util.List;
import java.util.Optional;

public interface Database {
    List<OrderStatusModel> listAllOrderStatuses();
    Optional<OrderStatusModel> findOrderStatusWithName(String orderStatusName);
    Optional<OrderStatusModel> findOrderStatusById(int orderStatusId);
    Optional<OrderModel> findOrderById(int orderId);
    void updateOrder(OrderModel order);
}
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class InMemoryTestDatabase implements Database {
    List<OrderStatusModel> orderStatuses = new ArrayList<>();
    List<OrderModel> orders = new ArrayList<>();

    public InMemoryTestDatabase() {
        // populate with dummy sample data.
        orderStatuses.add(new OrderStatusModel(1, "Order Taken"));
        orderStatuses.add(new OrderStatusModel(2, "Order Processing"));
        orderStatuses.add(new OrderStatusModel(3, "Shipped"));

        orders.add(
                new OrderModel(
                        123,
                        "XYZZY",
                        findOrderStatusById(1)
                                .orElse(null)
                )
        );
    }

    public List<OrderStatusModel> listAllOrderStatuses() {
        return orderStatuses;
    }

    @Override
    public Optional<OrderStatusModel> findOrderStatusWithName(String orderStatusName) {
        return orderStatuses.stream()
                .filter(orderStatus -> orderStatusName.equals(orderStatus.orderStatusNameProperty().get()))
                .findFirst();
    }

    @Override
    public Optional<OrderStatusModel> findOrderStatusById(int orderStatusId) {
        return orderStatuses.stream()
                .filter(orderStatus -> orderStatusId == orderStatus.orderStatusIdProperty().get())
                .findFirst();
    }

    public Optional<OrderModel> findOrderById(int orderId) {
        return orders.stream()
                .filter(order -> orderId == order.orderNumberProperty().get())
                .findFirst();
    }

    public void updateOrder(OrderModel order) {
        for (int i = 0; i < orders.size(); i++) {
            if (orders.get(i).orderNumberProperty().get() == order.orderNumberProperty().get()) {
                orders.set(i, order);
                break;
            }
        }
    }
}
import javafx.beans.property.*;

public class OrderModel {

    private final IntegerProperty orderNumber;
    private final StringProperty customerName;
    private final ObjectProperty<OrderStatusModel> orderStatus;

    public OrderModel(int orderNumber, String customerName, OrderStatusModel orderStatus){
        this.orderNumber = new SimpleIntegerProperty(orderNumber);
        this.customerName = new SimpleStringProperty(customerName);
        this.orderStatus = new SimpleObjectProperty<>(orderStatus);
    }

    public IntegerProperty orderNumberProperty() {
        return orderNumber;
    }

    public StringProperty customerNameProperty() {
        return customerName;
    }

    public ObjectProperty<OrderStatusModel> orderStatusProperty() {
        return orderStatus;
    }
}
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

import java.util.Objects;

public class OrderStatusModel {
    private final IntegerProperty orderStatusId;
    private final StringProperty orderStatusName;

    public OrderStatusModel(int orderStatusId, String orderStatusName){
        this.orderStatusId = new SimpleIntegerProperty(orderStatusId);
        this.orderStatusName = new SimpleStringProperty(orderStatusName);
    }

    public IntegerProperty orderStatusIdProperty() {
        return orderStatusId;
    }

    public StringProperty orderStatusNameProperty() {
        return orderStatusName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        OrderStatusModel that = (OrderStatusModel) o;
        return Objects.equals(orderStatusId.get(), that.orderStatusId.get()) &&
                Objects.equals(orderStatusName.get(), that.orderStatusName.get());
    }

    @Override
    public int hashCode() {
        return Objects.hash(orderStatusId.get(), orderStatusName.get());
    }
}