javaFX 文本字段和侦听器



我面临着有两个文本字段的情况,每个文本字段都有 2 个单独的侦听器。

TextField customerId 和 TextField customerName。

1000 莫汉

1002 米图恩

我正在尝试在填写一个文本字段时自动更新其他文本字段,例如,如果填写了 customerId 1000,则相应的客户名称 mohan 将更新为文本字段 customerName,如果填充了 mohan,那么他的客户 ID 1000 将被填充在 customerId 文本字段中。我正在使用地图,问题是当一个文本字段填充其侦听器时,调用该侦听器回调相同的文本字段侦听器,这会导致循环最终以大量错误结束。我应该怎么做才能解决这个问题?

最小示例

    Map<String, String> treeMapCustomerName,treeMapCustomerId;
     treeMapCustomerName=new TreeMap<String,String>();
     treeMapCustomerId=new TreeMap<String,String>();
String customerName="mohan";
String customerId="1000";
treeMapCustomerId.put("1000","Mohan");
treeMapCustomerId.put("1002","Mithun");
treeMapCustomerName.put("Mohan","1000");
treeMapCustomerName.put("Mithun","1002");


        customerName.textProperty().addListener((observable, oldValue, newValue) -> {
        customerId.setText(treeMapCustomerName.get(customerName));//immediately customerId textfield listener is triggered which will trigger this listener causing cycles  
        });
        customerId.textProperty().addListener((observable, oldValue, newValue) -> {
        customerName.setText(treeMapCustomerId.get(customerId));
        });

您没有利用新值,而是使用控件访问映射,这将在运行时引发错误

您可以检查地图是否包含您的密钥,并且仅更新其他文本字段(如果存在),如下所示:

            customerName.textProperty().addListener((observable, oldValue, newValue) -> {
                if(treeMapCustomerName.containsKey(newValue)){
                    customerId.setText(treeMapCustomerName.get(newValue));
                }
            });
            customerId.textProperty().addListener((observable, oldValue, newValue) -> {
                if(treeMapCustomerId.containsKey(newValue)){
                    customerName.setText(treeMapCustomerId.get(newValue));
                }
            });

这将避免在输入完整的 id/用户名之前检查地图的问题,但这不会考虑输入的值是另一个值的子字符串的问题。

例如,如果映射包含 id 的 100、1000、10000,

并且您不希望其中每个都显示为用户键入 10000,则可能需要额外的控件,例如按钮,而不是使用该属性

最新更新