【问题标题】:Remove a button by clicking on it in JavaFX通过在 JavaFX 中单击来删除按钮
【发布时间】:2020-04-07 04:10:38
【问题描述】:

我正在使用 JavaFX 构建一个日历/计划器应用程序。该应用程序由一个带有 35 (7x5) 个 VBox 的 GridPane 组成。在这些 VBox 中是 TaskButtons(在下面实现)。当我右键单击任务框时,它会将文本变为灰色,当我左键单击 TsskButton 时,我希望它删除按钮。我已经知道的事情。

  1. AnchorPaneNode(扩展 VBox)没有静态 getChildren() 方法。
  2. 我无法为窗格创建单独的实例变量,因为我不知道我将拥有多少个。
  3. getParent().getChildren() 不起作用,因为 getChildren() 的 parents 方法不可见。
  4. VBox 有一个公共的 getChildren(),但它不是静态的。
  5. 我尝试为 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;");
            }           
        });
    }
}

【问题讨论】:

  • 我认为这会有所帮助。 stackoverflow.com/questions/29722232/…
  • @KumarAnilChaurasiya 我已经看到了这个帖子,不幸的是它没有帮助。这个解决方案为 VBox 设置了一个实例变量,我想不惜一切代价避免,因为我的应用程序中很可能有数百个甚至数千个 VBox。不过还是谢谢你的建议!

标签: java javafx javafx-11


【解决方案1】:

找到了我自己问题的答案! 对于那些遇到同样问题的人,这就是我为解决它所做的:

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”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-29
    • 2015-02-03
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多