Removing object from scene in javafx


Question

I am digging the documentation to see if there's a remove method, I just get this link whenever I google http://www.coderanch.com/t/580998/JavaFX/java/remove-node

there's a simple remove option Eg : .getChildren().remove(object)

It does not seem to work for me !

1
1
3/27/2014 3:21:58 PM

The code which you've provided works fine with me.

Add circle with ALT+Click, and remove them by simply clicking on them.

The reason I've used the ALT key for adding the circles is because in the below code, both the scene and the circles handle mouse clicks. Thus, the code has to know from where the event is coming from. This is just an example, of course.

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class ChangeListenerSample extends Application {

    public static void main(final String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Group root = new Group();
        primaryStage.setResizable(false);
        final Scene scene = new Scene(root, 400,80);
        primaryStage.setScene(scene);

        scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

            @Override public void handle(final MouseEvent event)
            {
                if (!event.isAltDown())
                    return;

                final Circle circle = new Circle(event.getSceneX(), event.getSceneY(),30);
                circle.setFill(Color.YELLOW);
                root.getChildren().add(circle);

                circle.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

                    @Override public void handle(final MouseEvent arg0)
                    {
                        root.getChildren().remove(circle);
                    }
                });
            }
        });

        primaryStage.show();
    }

}
1
3/27/2014 3:43:53 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon