简体   繁体   中英

Remove a button by clicking on it in JavaFX

I am building a calander/planner application using JavaFX. The app consists of a single GridPane with 35 (7x5) VBox's. Within these VBox's are TaskButtons (implemented below). When I right click a TaskBox it will turn the text to grey and when I left click the TsskButton I want it to delete the button. Things I know already.

  1. AnchorPaneNode (extends VBox) doesn't have a static getChildren() method.
  2. I cannot create a separate instance variable for pane since I will not know how many I will have.
  3. getParent().getChildren() doesn't work because the parents method of getChildren() is not visible.
  4. VBox has a public getChildren(), but it is not static.
  5. I tried to make a static accessor to getChildren(), but was unable to.

What else can I try to get this button removed when right clicking? Thank you for your help!

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;");
            }           
        });
    }
}

Found the answer to my own question: For those that run into the same issue this is what I did to solve it:

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;");
    }           
});

I needed to access the public getChildren() that VBox provides and I did so by casting (this)getParent() to a VBox. From there I was able to getChildren() and remove "this".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM