JavaFX focusedProperty()。addListener重构代码

时间:2018-04-26 02:29:46

标签: java javafx refactoring listener

我在表单上有文本字段,当字段不在焦点时我执行操作。我为每个字段都有一个单独的监听器代码,并且想知道如何合并这个代码,以便所有字段都有一个监听器代码,因为我有重复的代码,唯一不同的是文本字段名称。

@Override
    public void initialize(URL url, ResourceBundle rb) {


        callPremium.focusedProperty().addListener(new ChangeListener<Boolean>()
        {
            @Override
            public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
            {
                if (newPropertyValue == false && !callPremium.getText().trim().isEmpty())
                {
                    SIMTradeCalculatorModel model = new SIMTradeCalculatorModel(numShares, purchasePrice, brokerage, callStrikePrice, putStrikePrice, putPremium, callPremium);
                    model.validateDecimal(callPremium, errorDisplay, performCalculationButton);
                    model.checkAllFields(performCalculationButton);
                }
                else {
                    callPremium.setText(callPremium.getText().trim());
                }
            }
        });

        putPremium.focusedProperty().addListener(new ChangeListener<Boolean>()
        {
            @Override
            public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
            {
                if (newPropertyValue == false && !putPremium.getText().trim().isEmpty())
                {
                    SIMTradeCalculatorModel model = new SIMTradeCalculatorModel(numShares, purchasePrice, brokerage, callStrikePrice, putStrikePrice, putPremium, callPremium);
                    model.validateDecimal(putPremium, errorDisplay, performCalculationButton);
                    model.checkAllFields(performCalculationButton);
                }
                else {
                    putPremium.setText(putPremium.getText().trim());
                }
            }
        });
}

1 个答案:

答案 0 :(得分:0)

使用重复代码做你总是做的事情:定义一个封装重复的方法,并对不同的部分进行参数化:

private ChangeListener<Boolean> createListener(TextInputControl control) {

    return (obs, oldValue, newValue) -> {
        if ((! newValue) && ( !control.getText().trim().isEmpty() )) {
            SIMTradeCalculatorModel model = new SIMTradeCalculatorModel(numShares, purchasePrice, brokerage, callStrikePrice, putStrikePrice, putPremium, control);
                model.validateDecimal(control, errorDisplay, performCalculationButton);
                model.checkAllFields(performCalculationButton);
            } else {
                control.setText(control.getText().trim());
            }
        }
    };
}

然后

callPremium.focusedProperty().addListener(createListener(callPremium));
putPremium.focusedProperty().addListener(createListener(putPremium));