2017-03-23 41 views
1

PictureJavaFX的我想刪除動態元素在手風琴

問:我如何刪除我右擊的元素?例如:World Pane2 Click和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); 
    } 
}); 

回答

0

要從手風琴刪除名爲窗格中,當你右鍵點擊標題窗格:

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; 
    } 
} 
+0

太謝謝你了。你的回覆工作。他現在正在以一種健康的方式工作。 –

+0

該系統不允許我給你分。非常感謝你。 –