首页 > 解决方案 > 如何从组合框中删除选定的元素

问题描述

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

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

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

输出:

在此处输入图像描述

标签: javafxcombobox

解决方案


由于onAction之前调用的ComboBox已正确处理更新本身,因此您需要使用以下命令延迟删除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);
            });
        }
    }
};

推荐阅读