0

我有一个ChoiceBox并且我想在用户扩展它时刷新它的内容。我还没有找到合适的听众。谷歌提供的所有东西都与处理ChangeValue事件有关。

我认为我应该添加eventListener<ActionEvent>ChoiceBox因为我正在处理的是单击 a ChoiceBox,但我的实现不起作用。

ActionEvent 在我单击任何 List 值时触发,而不是在我单击ChoiceBox自身时触发。

4

1 回答 1

1

使用选择框注册一个监听器showingProperty

choiceBox.showingProperty().addListener((obs, wasShowing, isNowShowing) -> {
    if (isNowShowing) {
        // choice box popup is now displayed
    } else {
        // choice box popup is now hidden
    }
});

这是一个快速演示:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ChoiceBoxPopupTest extends Application {


    private int nextValue ;

    @Override
    public void start(Stage primaryStage) {
        ChoiceBox<Integer> choiceBox = new ChoiceBox<>();
        choiceBox.getItems().add(nextValue);
        choiceBox.setValue(nextValue);
        choiceBox.showingProperty().addListener((obs, wasShowing, isNowShowing) -> {
            if (isNowShowing) {
                choiceBox.getItems().setAll(++nextValue, ++nextValue, ++nextValue);
            }
        });
        BorderPane root = new BorderPane();
        root.setTop(choiceBox);
        BorderPane.setAlignment(choiceBox, Pos.CENTER);
        root.setPadding(new Insets(5));
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
于 2017-11-27T22:28:33.877 回答