JavaFx ComboBox valueProperty().addListener(new ChangeListener<String>() 逐步重复

JavaFx ComboBox valueProperty().addListener(new ChangeListener<String>() progressively repeated

我在 JavaFX 项目上使用 ComboBox。当我使用 valueProperty().addListener(new ChangeListener()) 每次点击都会逐步重复此操作

这是我的控制器:

public class Controller  {

// some code 

@FXML
private ComboBox<String> FruitList;


int count = 1;

public void comboAction() {
        FruitList.valueProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                System.out.println("Selected value : " + newValue);
            }
        });
    //count number of select actions
    System.out.println("Selection number: " + count++);

    }
}

我的 FXML 文件:

<!--some code-->

<ComboBox fx:id="FruitList" onAction="#comboAction" layoutX="22.0" layoutY="212.0" prefHeight="25.0" prefWidth="234.0" promptText="Choose the current month">
        <items>
            <FXCollections fx:factory="observableArrayList">
                <String fx:value="Apple" />
                <String fx:value="Orange" />
                <String fx:value="Pear" />
            </FXCollections>
        </items>
</ComboBox>

<!--some code-->

输出结果

Selection number: 1

Selected value : Apple

Selection number: 2

Selected value : Pear

Selected value : Pear

Selection number: 3

Selected value : Orange

Selected value : Orange

Selected value : Orange

Selection number: 4

Selected value : Apple

Selected value : Apple

Selected value : Apple

Selected value : Apple

Selection number: 5 Selected value : Pear

Selected value : Pear

Selected value : Pear

Selected value : Pear

Selected value : Pear

Selected value : Pear

如果你看一下 onActionProperty:

The ComboBox action, which is invoked whenever the ComboBox value property is changed.

所以当你这样做时:

<ComboBox fx:id="FruitList" onAction="#comboAction" ...>

每次更改值时都会执行comboAction()方法。

但是在这种方法中,您向 valueProperty 添加了一个新的(并且每次都是额外的)侦听器,当值下次更改时,该侦听器也将被执行。一次又一次。因此,每次值更改时,您都会有一个额外的侦听器。

在不添加新侦听器的情况下获取侦听器方法主体并将其插入外部方法主体的明显修复:

public void comboAction() {
    System.out.println("Selected value : " + FruitList.getValue());
}