簡體   English   中英

通過單擊 JavaFX 中的按鈕來刪除它

[英]Remove a button by clicking on it in JavaFX

我正在使用 JavaFX 構建一個日歷/規划器應用程序。 該應用程序由一個帶有 35 (7x5) 個 VBox 的 GridPane 組成。 在這些 VBox 中是 TaskButtons(在下面實現)。 當我右鍵單擊任務框時,它會將文本變為灰色,當我左鍵單擊 TsskButton 時,我希望它刪除按鈕。 我已經知道的事情。

  1. AnchorPaneNode(擴展 VBox)沒有 static getChildren() 方法。
  2. 我無法為窗格創建單獨的實例變量,因為我不知道我將擁有多少。
  3. getParent().getChildren() 不起作用,因為 getChildren() 的 parents 方法不可見。
  4. VBox 有一個公共的 getChildren(),但它不是 static。
  5. 我試圖為 getChildren() 制作一個 static 訪問器,但無法做到。

右鍵單擊時,我還能嘗試刪除此按鈕嗎? 謝謝您的幫助!

public class TaskButton extends Button {

    protected int buttonNum = AnchorPaneNode.listIndex;
    public TaskButton(String str)
    {
        super(str);

        setStyle("-fx-background-color: transparent;");


        setOnMouseClicked(e -> {
            if(e.getButton() == MouseButton.SECONDARY) 
            {
                //I want to remove this button from the VBox, neither of these work
                AnchorPaneNode.getChildren().remove(this);
                //or
                getParent().getChildren().remove(this);
            }
            else if(e.getButton() == MouseButton.PRIMARY) 
            {
                setStyle("-fx-background-color: transparent; -fx-text-fill: #666666;");
            }           
        });
    }
}

找到了我自己的問題的答案:對於那些遇到同樣問題的人來說,這是我為解決它所做的:

setOnMouseClicked(e -> {
    if (e.getButton() == MouseButton.SECONDARY) {
        //I want to remove this button from the VBox, neither of these work
        //AnchorPaneNode.getChildren().remove(this);
        //or
        VBox vbox = (VBox) getParent();
        vbox.getChildren().remove(this);
    } else if (e.getButton() == MouseButton.PRIMARY) {
        setStyle("-fx-background-color: transparent; -fx-text-fill: #666666;");
    }           
});

我需要訪問 VBox 提供的公共 getChildren(),我通過將 (this)getParent() 轉換為 VBox 來做到這一點。 從那里我能夠 getChildren() 並刪除“this”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM