[英]Remove a button by clicking on it in JavaFX
我正在使用 JavaFX 構建一個日歷/規划器應用程序。 該應用程序由一個帶有 35 (7x5) 個 VBox 的 GridPane 組成。 在這些 VBox 中是 TaskButtons(在下面實現)。 當我右鍵單擊任務框時,它會將文本變為灰色,當我左鍵單擊 TsskButton 時,我希望它刪除按鈕。 我已經知道的事情。
右鍵單擊時,我還能嘗試刪除此按鈕嗎? 謝謝您的幫助!
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.