JavaFX does not repaint when removing an object drawn on top of another object - javafx

In the code below, the green rectangle is not removed on mouse click. However, if you resize the stage after the mouse click, the scene is repainted and the green rect vanishes.
If you set the green rectangle's size to 150/150, then some of it is immediately on top of the pane, and it vanishes immediately on mouse click.
Is this a JavaFX bug, or am I overlooking something?
How can I make the rectangle disappear on mouse click?
My environment: Windows 7 / Java 1.8.0 64-Bit Server VM build 25.0-b70.
package xschach.client;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main3 extends Application {
public static void main(String[] args) {
Application.launch(Main3.class.getName());
}
public Main3() {}
#Override
public void start(Stage stage) throws Exception {
Pane pane = new Pane();
Rectangle rect = new Rectangle(10, 10, 200, 200);
pane.getChildren().add(rect);
stage.setScene(new Scene(pane, 300, 300));
stage.show();
Rectangle rect2 = new Rectangle(100, 100, 50, 50);
rect2.setFill(Color.GREEN);
pane.getChildren().add(rect2);
pane.setOnMouseClicked(event -> pane.getChildren().remove(rect2));
}
}

It really seems to me a bug.
Doing some tests, what happens is the very last node (on top), no matter how many we have, that lays within the bounds of the first one, when it's removed, it is not visible to the scene graph, it's not marked as dirty, and no requestLayout() is called.
I've found also other workaround. Just allow some (minimal) transparency to the first child, and it will work...
rect.setFill(Color.web("000000FE"));
And you can always put this node behind the first one...
pane.setOnMouseClicked(event -> {
rect2.toBack();
pane.getChildren().remove(rect2);
});
Anyway, consider filing a bug to Jira.

I know it's a little bit late, but it might help someone.
If you use the method .clear() on the children list of the pane if forces the render of the view.
So this solution, quite extreme, I admit it, works :
pane.setOnMouseClicked(event -> {
pane.getChildren().clear();
pane.getChildren().add(rect);
});

I found another workaround. Move the node that is not erasing to the back with the toBack() method, and then move it back to its place with the toFront() method. This seems to activate the dirty mechanism and repaints the background node correctly.

Related

JavaFX - "Pointless" (CSS) Shadow Effect, Drastically decrices Graphics Performance

Hello, People [...]
🤔 Summary
Whenever i use Shadow-effect on my BorderPane or any Component/control/Element, the 3D Graphics performance (as seen, in the Preview section below) is getting way too low.
The "confusing" part is that, it even gets low performance when the effect is applied to something that really has nothing to do with my Tab, Subscene or even my moving Button, in a way [...]
I Use jdk-12.0.1.
👁️ Preview
⚠️ Recreating The Issue
Files Needed:
App.java | main.fxml | AnchorPane.css | MathUtils.java | SimpleFPSCamera.java
📝 General Code
(You can refer to Recreating The Issue Section for more Informations too)
AnchorPane.css
#BorderPane1 {
-fx-effect: dropshadow(three-pass-box, rgb(26, 26, 26), 50, 0.6, 0, 0); /* Comment it*/
}
App.java
public class App extends Application {
#FXML
public Parent root;
public TabPane TabPane1;
public BorderPane BorderPane1;
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
loader.setController(this);
root = loader.load();
Scene RootScene = new Scene(root, 1120, 540);
primaryStage.setScene(RootScene);
Thread t = new Thread() {
public void run() {
//Setting NewButton2
Button NewButton2 = new Button();
NewButton2.setId("Button2");
NewButton2.setText("test2");
NewButton2.setPrefWidth(150);
NewButton2.setPrefHeight(50);
NewButton2.setTranslateX(-75);
NewButton2.setTranslateY(-25);
NewButton2.setTranslateZ(900);
// Setting group
Group SubRootGroup = new Group(NewButton2);
SubRootGroup.setTranslateX(0);
SubRootGroup.setTranslateY(0);
SubRootGroup.setTranslateZ(0);
// Setting Scene
SubScene SubScene1 = new SubScene(SubRootGroup, 0, 0, true, SceneAntialiasing.BALANCED);
SubScene1.setId("SubScene1");
SubScene1.setFill(Color.WHITE);
SubScene1.heightProperty().bind(RootScene.heightProperty());
SubScene1.widthProperty().bind(RootScene.widthProperty());
// Initializing Camera
SimpleFPSCamera SimpleFPSCam = new SimpleFPSCamera();
// Setting Camera To The Scene
SubScene1.setCamera(SimpleFPSCam.getCamera());
// Adding Scene To Stage-TabPane.Tab(0)
TabPane1.getTabs().add(new Tab("Without Shadows"));
TabPane1.getTabs().get(0).setContent(SubScene1);
// Loading Mouse & Keyboard Events
SimpleFPSCam.loadControlsForSubScene(SubScene1);
}
};
t.setDaemon(true);
t.run();
primaryStage.show();
}
}
Things I 've Tried Until Now
javafx animation poor performance consumes all my cpu
setCache(true);
setCacheShape(true);
setCacheHint(CacheHint.SPEED);
(i have tried using it with all components without having any success [it might be my poor javaFX knowledge too , [using it in the wrong way?] ])
...
💛 Outro
Any Idea? Thanks In Advance, Any help will be highly appreciated, 💛 [...]
George.
Most probably, you will have figured this out by now, but since I was also banging my head about this same issue in the past, here is your answer:
The drop shadow effect is "expensive" and drawing it is slow. If you use it on a node with many descendants and move any of the descendants, it will cause the effect to be re-calculated on the parent, so the whole animation becomes slow (regardless if the parent itself is animated or not).
I solved this by using a StackPane as the top-most container, to which I added a Pane as a first child (which has the css drop-shadow effect) and the normal top-level container for the actual controls as a second child.
This way, the "shadow" pane is not updated when something is animated down the layout tree and, voila, you have a working drop-shadow effect without a performance hit :-)

JavafX & CSS - Move Node to Front

As the title basically. I have a node in JavaFX which I want to be displayed in front of all other nodes according to certain CSS rules. I do not want this to change the ordering of the nodes in my VBox which .toFront() appears to do. See this question.
Is this even possible?
EDIT: To clarify. The situation is the following. I have a VBox containing a bunch of tightly packed ImageViews. When I hover over one I want it to grow slightly to give it the feel that the image is being lifted off of the screen. But since the ImageViews are so tightly packed only the top edge grows (visibly). The bottom edge grows but is below the following image and cannot be seen.
EDIT 2: Upon request here is a screenshot of what I am doing.
The different colour gradients are ImageViews and as I hover over one it should grow as the top edge of the top gradient has in this image (look closely at the top right corner next to the X). However as is also visible in this image the bottom edge of this ImageView has become hidden by the next gradient in this VBox and the grow is not visible.
This sounds like the perfect situation for using the viewOrder property of Node added in Java 9. The viewOrder controls how Nodes are drawn in relation to other Nodes of the same Parent without changing the order of the Nodes in the child list. Here's the Javadoc:
Defines the rendering and picking order of this Node within its parent.
This property is used to alter the rendering and picking order of a
node within its parent without reordering the parent's children list.
For example, this can be used as a more efficient way to implement
transparency sorting. To do this, an application can assign the
viewOrder value of each node to the computed distance between that
node and the viewer.
The parent will traverse its children in decreasing viewOrder order.
This means that a child with a lower viewOrder will be in front of a
child with a higher viewOrder. If two children have the same
viewOrder, the parent will traverse them in the order they appear in
the parent's children list.
However, viewOrder does not alter the layout and focus traversal order
of this Node within its parent. A parent always traverses its children
list in order when doing layout or focus traversal.
Here's an example using this property:
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.ArrayList;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
var box = new HBox(createRectangles(Color.DARKBLUE, Color.FIREBRICK, 25));
box.setAlignment(Pos.CENTER);
box.setPadding(new Insets(50, 20, 50, 20));
primaryStage.setScene(new Scene(box));
primaryStage.show();
}
private Rectangle[] createRectangles(Color start, Color end, int count) {
var list = new ArrayList<Rectangle>(count);
for (double i = 0; i < count; i++) {
var rect = new Rectangle(30, 60, start.interpolate(end, i / count));
var scaleTrans = new ScaleTransition(Duration.millis(250), rect);
scaleTrans.setFromX(1.0);
scaleTrans.setFromY(1.0);
scaleTrans.setToX(1.2);
scaleTrans.setToY(1.2);
rect.setOnMouseEntered(e -> {
scaleTrans.stop(); // <--- doesn't seem necessary*
scaleTrans.setRate(1.0);
rect.setViewOrder(-1.0);
scaleTrans.play();
});
rect.setOnMouseExited(e -> {
scaleTrans.stop(); // <--- doesn't seem necessary*
scaleTrans.setRate(-1.0);
rect.setViewOrder(0.0);
scaleTrans.play();
});
// *the "stop()"'s don't seem to be necessary. When I commented
// them out the animation still worked. In fact, the animation
// actually seems smoother in the situation where you move the
// mouse over and then away quickly (before the zoom-in completes).
list.add(rect);
}
return list.toArray(new Rectangle[0]);
}
}
It uses Rectangles instead of ImageViews but the concept is the same. When the mouse hovers over a Rectangle it sets the view order to be lower than the others and then plays a ScaleTransition to make it bigger. When the mouse exits it resets the view order back to 0 and then reverses the ScaleTransition.
Note: I used the var keyword which was added in Java 10.
And here is a GIF of the example in action:
Edit: Since you brought up CSS I went and checked if the view order could be set from a stylesheet. And it appears it can. Looking at the CSS Reference Guide there is a CSS property defined for Node named -fx-view-order.
Here is one such solution, creating a new stage to show the zoomed in image.
I do not set the proper coordinates in this sample, but this works as a proof of concept.
In a nutshell: capture the onMouseEntered and onMouseExited events and hide or show the new stage.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
FlowPane root = new FlowPane();
root.setHgap(5);
root.setVgap(5);
for (int i = 0; i < 25; i++) {
root.getChildren().add(getImagePane());
}
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
private VBox getImagePane() {
VBox pane = new VBox() {{
setAlignment(Pos.CENTER);
setPadding(new Insets(5));
setWidth(50);
setHeight(50);
setStyle("-fx-border-color: black");
}};
ImageView img = new ImageView("sample/imageGallery/cerulean.png") {{
setFitWidth(50);
setFitHeight(50);
setPreserveRatio(true);
Stage stage = zoomedStage(pane, this);
setOnMouseEntered(mouseEvent -> stage.show());
setOnMouseExited(mouseEvent -> stage.hide());
}};
pane.getChildren().add(img);
return pane;
}
private Stage zoomedStage(VBox parent, ImageView img) {
Stage stage = new Stage();
stage.setWidth(110);
stage.setHeight(110);
VBox pane = new VBox() {{
setAlignment(Pos.CENTER);
setPadding(new Insets(5));
setWidth(110);
setHeight(110);
setStyle("-fx-border-color: black");
}};
pane.setPickOnBounds(false);
ImageView zoomedImage = new ImageView(img.getImage());
zoomedImage.setFitHeight(100);
zoomedImage.setFitWidth(100);
pane.getChildren().add(zoomedImage);
stage.setScene(new Scene(pane));
stage.initStyle(StageStyle.UNDECORATED);
return stage;
}
}
From here, it should just be a matter or fixing the stage's coordinates to be centered over the image and then remove the stage's decoration.
Known Issues:
You will also need to handle the issue with the mouse cursor being blocked by the new stage. This will lead to a loop where the mouse is constantly entering and exiting the thumbnail of the image, causing the zoomed in stage to flicker.
From my point of view, you have a VBox with spacing 0 so each ImageView is tightly packed to each other so the glow effect is not well visible in every image. In that case you could just add a margin each time you want to select an ImageView in order to 'help' the glowing effect to appear.
For Java 8 :
Sadly, this can't be happened from a CSS cause the ImageView does not provide any rule for setting margin or padding. So you are more or less (in my opinion) bound to write that behaviour through code.
:
private Node createImageView(String imageLink) {
// Setting the image view
ImageView imageView = new ImageView(imageLink);
// setting the fit width of the image view
imageView.setFitWidth(400);
// Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
// Instantiating the Glow class
Glow glow = new Glow();
imageView.setOnMouseEntered(e -> {
// setting level of the glow effect
glow.setLevel(0.9);
// Adding a margin on TOP and Bottom side just to make the
// glowing effect visible
VBox.setMargin(imageView, new Insets(2,0,2,0));
});
imageView.setOnMouseExited(e -> {
// remove the glow effect
glow.setLevel(0.0);
// remove the margins
VBox.setMargin(imageView, new Insets(0));
});
// Applying bloom effect to text
imageView.setEffect(glow);
return imageView;
}

Why does the application window only have a top and left inner border and how to do fix it?

After working with JavaFX applications on a daily basis for about one and a half year, I just recently noticed that the application window only has a inner border (the border separating the frame from the content inside the stage) on the top and left side of the window. And now when I've seen it, I can't unsee it.
Here's an MCVE displaying a empty application window:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MCVE extends Application {
#Override
public void start(Stage stage) {
AnchorPane pane = new AnchorPane();
stage.setScene(new Scene(pane, 800, 800));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
And here's the result:
If you zoom in you can clearly see what I mean:
Why is it designed like that? To me, it looks really weird. I'd like the window to have an inner border on all four sides, but maybe I'm missing some design principle here or something.
And how would I change the style of the application window so it has all four borders if I wanted to? The closest I could get was to set primaryStage.initStyle(StageStyle.UNIFIED); and then style the border of the window content pane instead. But the problem with this approach is that the standard inner border replicates the look of the outer border of the window, and just setting a custom border on the content pane somehow made it hard to replicate the style of the outer border perfectly. Either it looked too sharp or too blurry, or the color was wrong.

Frost Glass Effect with dynamic Background JavaFX

I'm Developing a JavaFX Application :
In here, I want the Left Pane to have a Blur Background Effect, i.e, when ever the user scrolls the map, the Content Behind the Left Pane Changes, and i want to Use That Content(Blurred), as the Background of the left Pane. & i've almost done it.
Whenever I scroll the Map, it does work, and content Behind gets updated, but In the System Monitor i can see the CPU usage, Temperature and Overall Power Usage Drastically Rises.
To achieve the Frost Glass Effect, I've Added a Event Listener(for detecting mouse move) to the webEngine(Contains the Map) :
Document doc = webEngine.getDocument();
((EventTarget) doc).addEventListener("mousemove", listener, false);
Listener Executes a Method Which :
Retrieves the Actual Content Beneath the Left Pane(Map).
Blur's the Image.
Updates the Screen
To Update the Screen, the Method removes, the Left Pane(VBox) and the Previous Image(Which was The Background). & then again First Add's the Blurred Image Pane and Then the Left Pane to the Root Pane.
So, I think the reason I'm having Performance Issues with this is because, it has to very rapidly remove and Add Panes(Left Pane and Background Image), to the Root Pane, while the user is dragging the Map.
Problem : Very High CPU Usage
So, Is there any other Approach in JavaFX, Wherein it does not require, such high CPU Usage ?
Something Like, which doesn't require removing and Adding Panes all the time.
Create two panes in a HBox, render a view of the relevant section of the map into each pane. Set a blur effect on the left pane. No listeners, snapshots or dynamic adding or removing of panes is required.
Try a couple of different blur effects (there is BoxBlur and GuassianBlur) with different settings, if needed, to adjust performance characteristics.
setting the Blur effect directly on the left Pane, blur's everything (Button text), and as i've set Transparency effect, this setup only blur's the left Pane,
Use a stackpane for the left pane with the left map section at the bottom of stack (with the blur effect applied to it) and the transparent overlay at the top of the stack (with no effect applied to it).
Is there a way , i can blur a part of a pane, so the part lying under the left Pane could be selected & blurred?
Yes, you use a technique similar to:
How to implement a transparent Pane with non-transparent children?
Frosted Glass Effect in JavaFX?
Sample
Here is a quick sample, just as a proof of concept, obviously for your solution you will need something slightly different.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
/**
* Constructs a scene with a pannable Map background.
*/
public class FrostedPannableView extends Application {
private Image backgroundImage;
private static final double W = 800;
private static final double H = 600;
#Override
public void init() {
backgroundImage = new Image("http://www.narniaweb.com/wp-content/uploads/2009/08/NarniaMap.jpg");
}
#Override
public void start(Stage stage) {
stage.setTitle("Drag the mouse to pan the map");
stage.setResizable(false);
// make a transparent pale blue overlay with non transparent blue writing on it.
final Label label = new Label("Map\nof\nNarnia");
label.setTextAlignment(TextAlignment.CENTER);
label.setStyle("-fx-text-fill: midnightblue; -fx-font: bold italic 40 'serif'; -fx-padding: 0 0 20 0;");
StackPane glass = new StackPane();
StackPane.setAlignment(label, Pos.BOTTOM_CENTER);
glass.getChildren().addAll(label);
glass.setStyle("-fx-background-color: rgba(0, 100, 100, 0.5);");
glass.setMaxWidth(W * 1/4);
glass.setMaxHeight(H);
StackPane.setAlignment(glass, Pos.CENTER_LEFT);
// construct a partitioned node with left side blurred.
ImageView leftMap = new ImageView(backgroundImage);
ImageView rightMap = new ImageView(backgroundImage);
// wrap the partitioned node in a pannable scroll pane.
ScrollPane leftScroll = createScrollPane(leftMap);
Rectangle leftClip = new Rectangle(W * 1/4, H);
leftScroll.setClip(leftClip);
leftScroll.setEffect(new GaussianBlur());
ScrollPane rightScroll = createScrollPane(rightMap);
Rectangle rightClip = new Rectangle(W * 1/4, 0, W * 3/4, H);
rightScroll.setClip(rightClip);
StackPane composite = new StackPane();
composite.getChildren().setAll(
leftScroll,
rightScroll
);
StackPane layout = new StackPane(
composite,
glass
);
// show the scene.
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
// bind the scroll values together and center the scroll contents.
leftScroll.hvalueProperty().bind(rightScroll.hvalueProperty());
leftScroll.vvalueProperty().bind(rightScroll.vvalueProperty());
rightScroll.setHvalue(rightScroll.getHmin() + (rightScroll.getHmax() - rightScroll.getHmin()) / 2);
rightScroll.setVvalue(rightScroll.getVmin() + (rightScroll.getVmax() - rightScroll.getVmin()) / 2);
}
/**
* #return a ScrollPane which scrolls the node.
*/
private ScrollPane createScrollPane(Node node) {
ScrollPane scroll = new ScrollPane();
scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scroll.setPannable(true);
scroll.setMinSize(ScrollPane.USE_PREF_SIZE, ScrollPane.USE_PREF_SIZE);
scroll.setPrefSize(W, H);
scroll.setMaxSize(ScrollPane.USE_PREF_SIZE, ScrollPane.USE_PREF_SIZE);
scroll.setContent(node);
return scroll;
}
public static void main(String[] args) {
launch(args);
}
}

Is there are any implementation of rectangle selection in javafx?

I mean like in file managers, when you would click, drag the mouse, creating a rectangle selection and after the mouse released selection is created?
I could do that like this (pseude-code like):
onMousePressed:
setGestureStarted(true)
onMouseMoved:
if isGestureStarted:
changeRectangle(event.getX, event.getY)
onMouseReleased:
select(getSelectionRectange())
But I thought that it's pretty common behavior and maybe it's already in framework.
EDIT1:
I was trying to do zoomable linechart. And I actually came across library to do that.
It's pretty good, but could be better though.
Right now I'm considering the actual worth of javaFX in our web project, because I don't like how such thing as zoomable chart is not in the library. Probably would be better with javascript (except I should learn it first, but It shouldn't be that hard).
You would probably need to make your own implementation for this. I found your pseudo code is quiet good. If you like to select for any component then you need to first create a simple rectangular boundary which is easily possible by your pseudo code.
Now for finding out either your node is inside that boundary then you need to do iteration of all the nodes/children of certain Parent Object by using this function: Node Intersect check
I would suggest to use that function after the onMouseReleased or if you like to see things in realtime then it is preferable in onMouseMoved
Your question asks "Is there any implementation of rectangle selection in JavaFX?"
The answer is "yes".
SceneBuilder implements drag-select functionality.
SceneBuilder is open source, so take a look through the source if you are interested on how this behaviour is achieved in JavaFX by SceneBuilder.
SceneBuilderKit is the framework from which SceneBuilder is derived, its source is at the link I provided.
From the SceneBuilder release notes:
JavaFX Scene Builder Kit is an API that allows the integration of Scene Builder panels and functionalities directly into the GUI of a larger application, or a Java IDE, such as NetBeans, IntelliJ, and Eclipse.
where is documentation?
From the release notes:
The javafx_scenebuilder_kit_javadoc-2_0-ea--.zip file, which contains an API javadoc for the JavaFX Scene Builder Kit. You can download the zip file from http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html.
The javafx_scenebuilder_kit_samples-2_0-ea--.zip file, which contains the SceneBuilderHello sample application that shows a minimal Java source code example of how the Scene Builder Kit API can be used. This sample is delivered as a NetBeans project. It can be downloaded from http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html.
Perhaps after you investigate, SceneBuilder and SceneBuilderKit might not be what you are looking for. In which case, edit your question to make it more explicit and perhaps include source for your rectangle selection implementation attempt and more detail on your requirements (what you intending to select, an image showing how the feature works, etc).
yes, in jfxtras-labs project via:
MouseControlUtil.addSelectionRectangleGesture(Parent root, Rectangle rect)
or
MouseControlUtil.addSelectionRectangleGesture(Parent root, Rectangle rect, EventHandler<MouseEvent> dragHandler, EventHandler<MouseEvent> pressHandler, EventHandler<MouseEvent> releaseHandler)
more info: http://jfxtras.org/doc/8.0labs/jfxtras/labs/util/event/MouseControlUtil.html
Note that selection behavior is extremely application specific and the class above is just a helper class to help you with selection gesture implementations. In the end you have to implement selection behavior yourself.
For a more detailed and matured example of node selection in JavaFx see my other answer here.
Edit: Basic Demo
This is the basic usage. Note that it's just a demo and should NOT be considered final or production ready! For more complex implementation of selection behavior you should tailor it (mostly mouse handlers) on your own based on your application's specific requirements.
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import jfxtras.labs.util.event.MouseControlUtil;
public class ShapeSelectionExample extends Application {
private List<Shape> selected = new ArrayList<>();
#Override
public void start(Stage primaryStage) {
final Group shapesGroup = new Group();
final AnchorPane root = new AnchorPane(shapesGroup);
// Add whatever shapes you like...
Rectangle shape1 = new Rectangle(200, 20, 50, 50);
Rectangle shape2 = new Rectangle(300, 60, 50, 50);
Circle shape3 = new Circle(100, 100, 30);
shapesGroup.getChildren().addAll(shape1, shape2, shape3);
final Rectangle selectionRect = new Rectangle(10, 10, Color.TRANSPARENT);
selectionRect.setStroke(Color.BLACK);
EventHandler<MouseEvent> mouseDragHanlder = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
for (Node shape : shapesGroup.getChildren()) {
handleSelection(selectionRect, (Shape) shape);
}
}
};
// Add selection gesture
MouseControlUtil.addSelectionRectangleGesture(root, selectionRect, mouseDragHanlder, null, null);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
}
private void handleSelection(Rectangle selectionRect, Shape shape) {
if(selectionRect.getBoundsInParent().intersects(shape.getBoundsInParent())) {
shape.setFill(Color.RED);
if(!this.selected.contains(shape))
this.selected.add(shape);
} else {
shape.setFill(Color.BLACK);
this.selected.remove(shape);
}
System.out.println("number of selected items:" + this.selected.size());
}
public static void main(String[] args) {
launch(args);
}
}
This is how the result would look like:
You could also write mouse press and release handlers (currently null in this code) to handle selection behavior while mouse button is pressed or released (which is different to mouse drag).

Resources