我正在使用 JavaFX 构建日历/规划器应用程序。该应用程序由一个 GridPane 和 35 (7x5) VBox 组成。这些 VBox 中包含任务按钮(如下实现)。当我右键单击任务框时,它会将文本变成灰色,当我左键单击 TsskButton 时,我希望它删除该按钮。我已经知道的事情。
- AnchorPaneNode(扩展 VBox)没有静态 getChildren() 方法。
- 我无法为 Pane 创建单独的实例变量,因为我不知道我将拥有多少个实例变量。
- getParent().getChildren() 不起作用,因为 getChildren() 的parents 方法不可见。
- VBox 有一个公共(public) getChildren(),但它不是静态的。
- 我尝试为 getChildren() 创建一个静态访问器,但失败了。
右键单击时我还可以尝试什么来删除此按钮?感谢您的帮助!
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 提供的公共(public) getChildren(),我通过将 (this)getParent() 转换为 VBox 来实现。从那里我能够 getChildren() 并删除“this”。
关于java - 在 JavaFX 中单击按钮即可将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61072703/