有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java javaFX文本字段和侦听器

我面临的情况是,有两个文本字段,每个字段有两个独立的侦听器

TextField customerId和TextField customerName

1000 mohan

1002 mithun

当一个文本字段被填充时,我试图自动更新其他文本字段,例如,如果customerId 1000被填充,则相应的客户名称mohan将被更新为文本字段customerName,如果mohan被填充,则其客户id 1000将被填充到customerId文本字段。我使用的是映射,问题是当一个文本字段填充它的侦听器被调用时,调用的是同一个文本字段侦听器,这导致循环最终以lot off错误结束。我该怎么解决这个问题

最小示例

    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));

        });

共 (1) 个答案

  1. # 1 楼答案

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

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

                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时显示其中的每一个,则您可能需要一个附加控件,例如按钮,而不是使用属性