如何从组合框删除选定的元素

时间:2019-07-01 10:34:54

标签: javafx combobox

当我从组合框中选择元素时,必须将其从元素列表中删除。并且所选元素不得显示,必须立即删除。

当我从组合框中选择元素时,必须将其从元素列表中删除。并且所选元素不得显示,必须立即删除。

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
public class Test extends Application {

    // Launch the application 
    public void start(Stage stage)
    {
        // Set title for the stage 
        stage.setTitle("creating combo box ");

        // Create a tile pane 
        TilePane r = new TilePane();

        // Create a label 
        Label description_label =
                new Label("This is a combo box example ");

        // Weekdays 
        String week_days[] =
                { "Monday", "Tuesday", "Wednesday",
                        "Thrusday", "Friday" };

        // Create a combo box 
        ComboBox combo_box =
                new ComboBox(FXCollections
                        .observableArrayList(week_days));

        // Label to display the selected menuitem 
        Label selected = new Label("default item selected");

        // Create action event 
        EventHandler<ActionEvent> event =
                new EventHandler<ActionEvent>() {
                    public void handle(ActionEvent e)
                    {
                        selected.setText(combo_box.getValue() + " selected");
                    }
                };

        // Set on action 
        combo_box.setOnAction(event);

        // Create a tile pane 
        TilePane tile_pane = new TilePane(combo_box, selected);

        // Create a scene 
        Scene scene = new Scene(tile_pane, 200, 200);

        // Set the scene 
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String args[])
    {
        // Launch the application 
        launch(args);
    }
}

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

由于onActionComboBox正确处理自身更新之前已被调用,因此您需要使用Platform.runLater延迟删除:

EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
    public void handle(ActionEvent e) {
        String value = combo_box.getValue();
        if (value != null) {
            selected.setText(value + " selected");
            Platform.runLater(() -> {
                combo_box.setValue(null);
                combo_box.getItems().remove(value);
            });
        }
    }
};