Javafx我想删除Accordion中的动态元素

时间:2017-03-23 21:19:19

标签: javafx dynamic removechild

Picture

问题:如何删除我右键单击的元素?示例:World Pane2 Click And World Pane2 Remove。

下面是单击按钮时动态创建元素的代码。 按钮单击:

 AnchorPane newPanelContent = new AnchorPane();
    VBox h = new VBox(10);
    h.setPadding(new Insets(10, 0, 0, 10));
    newPanelContent.getChildren().add(h);
    h.getChildren().add(new Label("Hello World"));
    h.getChildren().add(new Button("Click"));
    TitledPane pane = new TitledPane("World Pane"+i, newPanelContent);
    System.out.println(accordion);
    accordion.getPanes().add(pane);

找到答案。 https://stackoverflow.com/a/42988381/6306993

pane.setOnMouseClicked(event -> {
    if (MouseButton.SECONDARY.equals(event.getButton())) {
        accordion.getPanes().remove(pane);
    }
});

1 个答案:

答案 0 :(得分:1)

要在右键单击标题窗格时从手风琴中删除标题窗格:

pane.setOnMouseClicked(event -> {
    if (MouseButton.SECONDARY.equals(event.getButton())) {
        accordion.getPanes().remove(pane);
    }
});

其中pane是对标题窗格的引用。

完整示例应用

sample app

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.util.stream.IntStream;

public class PaneRemoval extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private Accordion accordion = new Accordion();

    @Override
    public void start(Stage stage) {
        accordion.getPanes().addAll(
                IntStream.range(0, 5)
                        .mapToObj(this::createTitledPane)
                        .toArray(TitledPane[]::new)
        );

        StackPane root = new StackPane(accordion);
        root.setPadding(new Insets(10));
        stage.setScene(new Scene(root));
        stage.show();
    }

    private TitledPane createTitledPane(int i) {
        Pane content = new Pane();
        content.setPrefSize(100, 100);
        content.setStyle("-fx-background-color: cornsilk;");

        TitledPane pane = new TitledPane(i + "", content);

        pane.setOnMouseClicked(event -> {
            if (MouseButton.SECONDARY.equals(event.getButton())) {
                accordion.getPanes().remove(pane);
            }
        });

        return pane;
    }
}