Checking Collision of Shapes with JavaFX - javafx-2

I am trying to do some collision detection. For this test I am using simple rectangular Shape, and checking their Bound, to figure if they are colliding. Although the detection does not work as expected. I have tried using different ways to move the object(relocate, setLayoutX,Y) and also different bound checks (boundsInLocal,boundsInParrent etc) but I still cannot get this to work. As you can see the detection works only for one object, even when you have three objects only one detects collision. This is some working code demonstrating the problem:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.ArrayList;
public class CollisionTester extends Application {
private ArrayList<Rectangle> rectangleArrayList;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryStage.setTitle("The test");
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
rectangleArrayList = new ArrayList<Rectangle>();
rectangleArrayList.add(new Rectangle(30.0, 30.0, Color.GREEN));
rectangleArrayList.add(new Rectangle(30.0, 30.0, Color.RED));
rectangleArrayList.add(new Rectangle(30.0, 30.0, Color.CYAN));
for(Rectangle block : rectangleArrayList){
setDragListeners(block);
}
root.getChildren().addAll(rectangleArrayList);
primaryStage.setScene(scene);
primaryStage.show();
}
public void setDragListeners(final Rectangle block) {
final Delta dragDelta = new Delta();
block.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = block.getTranslateX() - mouseEvent.getSceneX();
dragDelta.y = block.getTranslateY() - mouseEvent.getSceneY();
block.setCursor(Cursor.NONE);
}
});
block.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
block.setCursor(Cursor.HAND);
}
});
block.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
block.setTranslateX(mouseEvent.getSceneX() + dragDelta.x);
block.setTranslateY(mouseEvent.getSceneY() + dragDelta.y);
checkBounds(block);
}
});
}
private void checkBounds(Rectangle block) {
for (Rectangle static_bloc : rectangleArrayList)
if (static_bloc != block) {
if (block.getBoundsInParent().intersects(static_bloc.getBoundsInParent())) {
block.setFill(Color.BLUE); //collision
} else {
block.setFill(Color.GREEN); //no collision
}
} else {
block.setFill(Color.GREEN); //no collision -same block
}
}
class Delta {
double x, y;
}
}

Looks like you have a slight logic error in your checkBounds routine - you are correctly detecting collisions (based on bounds) but are overwriting the fill of your block when you perform subsequent collision checks in the same routine.
Try something like this - it adds a flag so that the routine does not "forget" that a collision was detected:
private void checkBounds(Shape block) {
boolean collisionDetected = false;
for (Shape static_bloc : nodes) {
if (static_bloc != block) {
static_bloc.setFill(Color.GREEN);
if (block.getBoundsInParent().intersects(static_bloc.getBoundsInParent())) {
collisionDetected = true;
}
}
}
if (collisionDetected) {
block.setFill(Color.BLUE);
} else {
block.setFill(Color.GREEN);
}
}
Note that the check you are doing (based on bounds in parent) will report intersections of the rectangle enclosing the visible bounds of nodes within the same parent group.
Alternate Implementation
In case you need it, I updated your original sample so that it is able to check based on the visual shape of the Node rather than the bounding box of the visual shape. This lets you to accurately detect collisions for non-rectangular shapes such as Circles. The key for this is the Shape.intersects(shape1, shape2) method.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
import javafx.scene.shape.*;
public class CircleCollisionTester extends Application {
private ArrayList<Shape> nodes;
public static void main(String[] args) { launch(args); }
#Override public void start(Stage primaryStage) {
primaryStage.setTitle("Drag circles around to see collisions");
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
nodes = new ArrayList<>();
nodes.add(new Circle(15, 15, 30));
nodes.add(new Circle(90, 60, 30));
nodes.add(new Circle(40, 200, 30));
for (Shape block : nodes) {
setDragListeners(block);
}
root.getChildren().addAll(nodes);
checkShapeIntersection(nodes.get(nodes.size() - 1));
primaryStage.setScene(scene);
primaryStage.show();
}
public void setDragListeners(final Shape block) {
final Delta dragDelta = new Delta();
block.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = block.getLayoutX() - mouseEvent.getSceneX();
dragDelta.y = block.getLayoutY() - mouseEvent.getSceneY();
block.setCursor(Cursor.NONE);
}
});
block.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
block.setCursor(Cursor.HAND);
}
});
block.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
block.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
block.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
checkShapeIntersection(block);
}
});
}
private void checkShapeIntersection(Shape block) {
boolean collisionDetected = false;
for (Shape static_bloc : nodes) {
if (static_bloc != block) {
static_bloc.setFill(Color.GREEN);
Shape intersect = Shape.intersect(block, static_bloc);
if (intersect.getBoundsInLocal().getWidth() != -1) {
collisionDetected = true;
}
}
}
if (collisionDetected) {
block.setFill(Color.BLUE);
} else {
block.setFill(Color.GREEN);
}
}
class Delta { double x, y; }
}
Sample program output. In the sample the circles have been dragged around and the user is currently dragging a circle which has been marked as colliding with another circle (by painting it blue) - for demonstration purposes only the circle currently being dragged has it's collision color marked.
Comments based on additional questions
The link I posted to an intersection demo application in a prior comment was to illustrate the use of various bounds types rather than as a specific type of collision detection sample. For your use case, you don't need the additional complexity of the change listener and checking on various different kinds of bounds types - just settling on one type will be enough. Most collision detection is only going to be interested in intersection of visual bounds rather than other JavaFX bounds types such as the layout bounds or local bounds of a node. So you can either:
Check for intersection of getBoundsInParent (as you did in your original question) which works on the smallest rectangular box which will encompass the visual extremities of the node OR
Use the Shape.intersect(shape1, shape2) routine if you need to check based on the visual shape of the Node rather than the bounding box of the visual shape.
Should I be using setLayoutX or translateX for the rectangle
The layoutX and layoutY properties are intended for positioning or laying out nodes. The translateX and translateY properties are intended for temporary changes to the visual location of a node (for example when the node is undergoing an animation). For your example, though either property will work, it is perhaps better form to use the layout properties than the translate ones, that way if you did want to run something like a TranslateTransition on the nodes, it will be more obvious what the start and end translate values should be as those values will be relative to the current layout position of the node rather than the position in the parent group.
Another way you could use these layout and translate co-ordinates in tandem in your sample is if you had something like an ESC to cancel during the course of a drag operation. You could set layoutX,Y to the initial location of your node, start a drag operation which sets translateX,Y values and if the user presses ESC, set translateX,Y back to 0 to cancel the drag operation or if the user releases the mouse set layoutX,Y to layoutX,Y+translateX,Y and set translateX,Y back to 0. The idea is that the translation is values are used for a temporary modification of the visual co-ordinates of the node from it's original layout position.
will the intersect work even though the circles are animated? I mean without dragging the circle by mouse, what will happen if I made them to move around randomly. Will the colour change in this case also?
To do this, just change where the collision detection function is called and the collision handler invoked. Rather than checking for intersections based upon a mouse drag event (like the example above), instead check for collisions within a change listener on each node's boundsInParentProperty().
block.boundsInParentProperty().addListener((observable, oldValue, newValue) ->
checkShapeIntersection(block)
);
Note: if you have lots of shapes being animated, then checking for collisions once per frame within a game loop will be more efficient than running a collision check whenever any node moves (as is done in the boundsInParentProperty change listener above).
Additional info for handling input on non-rectangular shapes
For input detection not collision detection, so not directly related to your question, look at the node.pickOnBounds setting if you need mouse or touch interaction with a non-rectangular node.

Related

SVG Path Collision in javafx

My question today is relatively simple, is there a way to have collision handling with the Javafx implementation of an SVGPath? EX: if I drop a particle on the screen, and it encounter Any part of the svgPath, it'll signal a collision.
I tried using the regular bounds collision, but it gives me a bounding box that is gigantic for the SVGPath if the path is shaped like an 'L'
The path I'm specifically playing with is:
m 252,12.362183
c 1.03171,23.632637 -4.57241,55.427587 9,69 65.41611,65.416117 361.05896,43.999997 469,43.999997
Do I have to re-interpolate the line and have an array store a set of (x,y) positions which I constantly check against? that seems rather unwieldy, but I simply can't think of any other (simpler) ways?
The code I tried for the regular bounded collision is as follows:
observableBooleanValue colliding = Bindings.createBooleanBinding(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
return particle.getBoundsInParent().intersects(path.getBoundsInParent());
}
}, particle.boundsInParentProperty(), path.boundsInParentProperty());
System.out.println("path bounds: " + path.boundsInParentProperty());
colliding.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> obs,
Boolean oldValue, Boolean newValue) {
if (newValue) {
System.out.println("Colliding");
} else {
System.out.println("Not colliding");
}
}
});
note that a particle is simply a circle with radius 2, and the path is just an SVG path loaded up with the aforementioned svg.
-Will
small edit
So after looking into a few other methods, I got it where it'll get close to be an accurate collision, but it's still about 20% too early (it detects a collision before one actually h appens). almost as if the edges of the path are a bit 'blurry'.
code:
particle.layoutYProperty().addListener(new ChangeListener<Number>(){
#Override
public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
Shape intersect = Shape.intersect(path, particle);
if ((intersect.getBoundsInLocal().getHeight() != -1) && (intersect.getBoundsInLocal().getWidth() != -1)) {
System.out.println("Collison!");
}
}
});
I'm really pretty stumped as to why the edge of the svgpath would have such a large buffer on it.
code that creates the path:
/**
* This function helps to make the path for animating particles
*
* #throws IOException
*/
public void makePaths() throws IOException {
PathLoader loader = new PathLoader();
path = new SVGPath();
path.setContent(loader.getPath(1));
path.setStroke(Color.AQUA);
//path.setFill(Color.TRANSPARENT);
//path.setEffect(boxBlur);
}
the pathloader simply loads in exactly the path I mentioned up above, tried with and w/o the blur and the transparency, no effect in tightening up the path collision.

How to redirect MouseEvent.MOUSE_PRESSED to a different Node?

I have a Region called 'R', and a Node called 'N'. N is the only child on R. Consider this behaviour:
the user presses the left-mouse button on some part of R
N (which is somewhere else on R) moves so that it is centered on the spot where the user pressed
the user releases the left-mouse button, then presses it again without moving the mouse
with the left-mouse button still pressed, the user drags the mouse, and N now follows the mouse cursor around as it is dragged.
I have no problems implementing the behaviour I've just described. I put a MOUSE_PRESSED handler on R that implements step 2. And I put a MOUSE_DRAGGED handler on N that implements step 4. JavaFX automatically directs the MouseEvents to these handlers on R and N for the presses in step 1 and 3 respectively.
The Problem:
I need to do this WITHOUT step 3. That is, the user should not have to press-release-press-drag, but rather should simply press-drag, and N should "jump" to the mouse location on the "press", and then start receiving MOUSE_DRAGGED events immediately.
Unfortunately, this doesn't happen. The release-click that I'm trying to omit seems to be necessary, otherwise the drag events all happen on R instead of N.
I'm thinking the solution will involve redispatching the initial MOUSE_PRESSED, or something along those lines. Does anyone know a way to do this (or a better way to solve my problem?)
Node has api to mark it as the target of drag gestures:
public void startFullDrag()
Starts a full press-drag-release gesture with this node as gesture
source. This method can be called only from a DRAG_DETECTED mouse
event handler. More detail about dragging gestures can be found in the
overview of MouseEvent and MouseDragEvent.
Assuming circle being your currently active node in a pane (borrowing code/names from James's answer), the collaborators are handlers on
mousePressed on pane that snaps the position of circle to the the current location
dragDetected on pane that calls startsFullDrag on circle
dragAny on circle that does the actual moving
In code:
pane.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
}
});
pane.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
circle.startFullDrag();
}
});
circle.addEventHandler(MouseDragEvent.ANY, new EventHandler<MouseDragEvent>() {
#Override
public void handle(MouseDragEvent event) {
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
}
});
I chose the simplest node to work with for this, but I think this would work in general:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class ClickAndDragTest extends Application {
#Override
public void start(Stage primaryStage) {
final Pane pane = new Pane();
final Circle circle = new Circle(100, 100, 50, Color.CORNFLOWERBLUE);
pane.getChildren().add(circle);
pane.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
}
});
pane.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
}
});
final Scene scene = new Scene(pane, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How can I make a TextArea stretch to fill the content, expanding the parent in the process?

So I have a TextArea and as the user pastes paragraphs into it, or just writes in it, I want it to expand vertically to reveal all the available text. I.e. not to use a scrollbar in the text field itself... much like what happens on many web pages. Many users, myself included, don't like to be forced to edit in a small window. Exactly how Facebook status updates box works.
I've tried
myTextArea.autoSize()
wrapped in an
myTextArea.textProperty().addListener(new ChangeListener()....);
but that doesn't work. I think it's happy autosizing to its current size.
The left, right & top anchors are set to it's parent AnchorPane. I've tried it with the bottom attached and not attached. Ideally I'd like to grow the anchor pane as the textarea grows.
I don't mind reading the TextProperty and calculating a trigger size which I set myself... but this seems a hacky approach IF there is already a best practise. The number of properties and sub objects of javafx is sufficiently daunting that it seems like a good point to ask the question here, rather than trying to figure out how many pixels the font/paragraphs etc are taking up.
Update:
So I thought maybe I was overthinking it, and all I needed to do was to switch the scrollbars off and the rest would happen. Alas, looking for available fields and methods for "scroll", "vertical", "vbar" comes up with nothing I can use. ScrollTopProperty looks like it's for something else.
The problem; the height of textArea is wanted to be grown or shrunk while its text is changing by either user's typing or copy-pasting. Here is another approach:
public class TextAreaDemo extends Application {
private Text textHolder = new Text();
private double oldHeight = 0;
#Override
public void start(Stage primaryStage) {
final TextArea textArea = new TextArea();
textArea.setPrefSize(200, 40);
textArea.setWrapText(true);
textHolder.textProperty().bind(textArea.textProperty());
textHolder.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
#Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
if (oldHeight != newValue.getHeight()) {
System.out.println("newValue = " + newValue.getHeight());
oldHeight = newValue.getHeight();
textArea.setPrefHeight(textHolder.getLayoutBounds().getHeight() + 20); // +20 is for paddings
}
}
});
Group root = new Group(textArea);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
// See the explanation below of the following line.
// textHolder.setWrappingWidth(textArea.getWidth() - 10); // -10 for left-right padding. Exact value can be obtained from caspian.css
}
public static void main(String[] args) {
launch(args);
}
}
But it has a drawback; the textarea's height is changing only if there are line breaks (ie Enter keys) between multiple lines, if the user types long enough the text gets wrapped to multiple line but the height is not changing.
To workaround this drawback I added this line
textHolder.setWrappingWidth(textArea.getWidth() - 10);
after primaryStage.show();. It works well for long typings where user does not linebreaks. However this generates another problem. This problem occurs when the user is deleting the text by hitting "backspace". The problem occurs exactly when the textHolder height is changed and where the textArea's height is set to new value. IMO it maybe a bug, didn't observe deeper.
In both case the copy-pasting is handling properly.
Awaiting a better, i use this hacky solution.
lookup the vertical scrollbar of the textarea.
make it transparent
listen to its visible property
when the scrollbar become visible i add a row to the textarea.
The code:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class GrowGrowTextArea extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
AnchorPane root = new AnchorPane();
root.setStyle("-fx-padding:20;-fx-background-color:dodgerblue;");
final TextArea textArea = new TextArea();
AnchorPane.setTopAnchor(textArea, 10.0);
AnchorPane.setLeftAnchor(textArea, 10.0);
AnchorPane.setRightAnchor(textArea, 10.0);
root.getChildren().add(textArea);
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
ScrollBar scrollBar = lookupVerticalScrollBar(textArea);
scrollBar.setOpacity(0.0);
scrollBar.visibleProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> source,
Boolean wasVisible,
Boolean isVisible) {
if (isVisible) {
textArea.setPrefRowCount(textArea.getPrefRowCount() + 1);
textArea.requestLayout();
}
}
});
}
private ScrollBar lookupVerticalScrollBar(Node node) {
if (node instanceof ScrollBar && ((ScrollBar)node).getOrientation() == Orientation.VERTICAL) {
return (ScrollBar) node;
}
if (node instanceof Parent) {
ObservableList<Node> children = ((Parent) node).getChildrenUnmodifiable();
for (Node child : children) {
ScrollBar scrollBar = lookupVerticalScrollBar(child);
if (scrollBar != null) {
return scrollBar;
}
}
}
return null;
}
}
I had a similar problem with creating expanding TextArea. I was creating TextArea that looks like TextField and expand vertically every time when there is no more space in line.
I have tested all solutions that I could find on this topic on stack and other sources available. I found few good solutions but neither was good enough.
After many hours of fighting, I figured out this approach.
I extended TextArea class, override layoutChildren() method and add a listener on text height.
#Override
protected void layoutChildren() {
super.layoutChildren();
setWrapText(true);
addListenerToTextHeight();
}
private void addListenerToTextHeight() {
ScrollPane scrollPane = (ScrollPane) lookup(".scroll-pane");
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
StackPane viewport = (StackPane) scrollPane.lookup(".viewport");
Region content = (Region) viewport.lookup(".content");
Text text = (Text) content.lookup(".text");
text.textProperty().addListener(textHeightListener(text));
}
private InvalidationListener textHeightListener(Text text) {
return (property) -> {
// + 1 for little margin
double textHeight = text.getBoundsInLocal().getHeight() + 1;
//To prevent that our TextArena will be smaller than our TextField
//I used DEFAULT_HEIGHT = 18.0
if (textHeight < DEFAULT_HEIGHT) {
textHeight = DEFAULT_HEIGHT;
}
setMinHeight(textHeight);
setPrefHeight(textHeight);
setMaxHeight(textHeight);
};
}
I used some of the code found in the previous answers.
The growTextAreaIfNecessary method will increase the height of textArea until the scrollbar is not visible (limited to 20 lines in this example).
The problem with this approach is that the window needs to be redrawn several times until the perfect height is found.
private ScrollBar lookupVerticalScrollBar(Node node) {
if (node instanceof ScrollBar && ((ScrollBar) node).getOrientation() == Orientation.VERTICAL) {
return (ScrollBar) node;
}
if (node instanceof Parent) {
ObservableList<Node> children = ((Parent) node).getChildrenUnmodifiable();
for (Node child : children) {
ScrollBar scrollBar = lookupVerticalScrollBar(child);
if (scrollBar != null) {
return scrollBar;
}
}
}
return null;
}
private void growTextAreaIfNecessary(TextArea textArea) {
Platform.runLater(() -> {
ScrollBar lookupVerticalScrollBar = lookupVerticalScrollBar(textArea);
int prefRowCount = textArea.getPrefRowCount();
if (lookupVerticalScrollBar.isVisible() && prefRowCount < 20) {
textArea.setPrefRowCount(prefRowCount + 1);
System.out.println("increasing height to: " + (prefRowCount + 1));
growTextAreaIfNecessary(textArea);
}
});
}
I have tried many hacks, most of them had jitters while typing, this to me was the perfect result:
textArea.textProperty().addListener((obs,old,niu)->{
Text t = new Text(old+niu);
t.setFont(textArea.getFont());
StackPane pane = new StackPane(t);
pane.layout();
double height = t.getLayoutBounds().getHeight();
double padding = 20 ;
textArea.setMinHeight(height+padding);
});

How to make a JavaFX Group not move around when just adding children?

If you watch the following test, you'll see that all the circles move around instead of just a new one being added. It doesn't happen every time. I think it's only when the new child is outside the existing bounds. But how do I get it so that it will not move the group and all it's children when I add another circle, regardless of where I put the circle?
Note, that if I don't set the scale on the Group, they won't all move. So it's related to setting the scale.
import javafx.application.*;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.shape.*;
import javafx.stage.*;
import java.util.*;
public class GroupTest extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
Pane pane = new Pane();
Group root = new Group();
// NOTE: removing these two setScale* lines stops the undesirable behavior
root.setScaleX(.2);
root.setScaleY(.2);
root.setTranslateX(100);
root.setTranslateY(100);
root.layoutXProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
System.out.println("root layout: " + root.getLayoutX() + ", " + root.getLayoutY());
}
});
root.getChildren().addListener(new ListChangeListener<Node>() {
#Override public void onChanged(Change<? extends Node> change) {
System.out.println("root: " + root.getBoundsInParent());
System.out.println("root: " + root.getBoundsInLocal());
System.out.println("root: " + root.getLayoutBounds());
System.out.println("root: " + root.getLayoutX() + ", " + root.getLayoutY());
}
});
pane.getChildren().add(root);
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
stage.show();
new Thread(() -> {
Random r = new Random();
try {
while (true) {
expand = expand * 1.1;
Thread.sleep(700);
Platform.runLater(() -> {
root.getChildren().add(new Circle(r.nextInt((int)(1000*expand)) - 500*expand, r.nextInt((int)(1000*expand)) - 500*expand, r.nextInt(50)+30));
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
static double expand = 1.0;
}
First, I want to say that the behavior you see can be achieved through a much smaller program, let alone those calculations you do for the circles. r.nextInt(250) for the positions of the circles would have been enough to see the behavior and is much easier to see what happens. Also, for debugging, I added a visible rectangle to the pane that is bound to the Group's layoutbounds, where you can see what happens:
final Rectangle background = new Rectangle(0, 0, 0, 0);
root.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
#Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
background.setX(newValue.getMinX());
background.setY(newValue.getMinY());
background.setWidth(newValue.getWidth());
background.setHeight(newValue.getHeight());
}
});
background.setFill(null);
background.setStroke(Color.RED);
pane.getChildren().add(background);
So, what happens here?
From the Group's API:
Any transform, effect, or state applied to a Group will be applied to all children of that group. Such transforms and effects will NOT be included in this Group's layout bounds, however if transforms and effects are set directly on children of this Group, those will be included in this Group's layout bounds.
Looking at the result with your scale turned on:
You see that the bounds of the group are larger than whats inside. This is because of how the transformation is applied: The children of the group are transformed, but for the calculation of the bounds of the group the scaling is not considered. Thus, the group is on the pane where the union of the untransformed bounds of the circles are, then transformations for the circles are applied.
Compare with this statement with the result when the scaling is turned off:
To sum up, this is by design and not a weird behavior, because the Group is always as big and positioned accordingly where the union of its untransformed children bounds are.
EDIT
If you want the nodes to be scaled at the position they are and the group not move, I suggest to scale the children of the group directly. This implementation of your thread changes the scaling of the circles every 5 circles, but they stay at the same position:
new Thread(new Runnable() {
private int count = 0;
private double scale1 = .5;
private double scale2 = .2;
private double currentScale = scale1;
#Override
public void run() {
final Random r = new Random();
try {
while (true) {
expand = expand * 1.1;
Thread.sleep(700);
Platform.runLater(new Runnable() {
#Override
public void run() {
System.out.println(count);
Circle c = new Circle(r.nextInt(250), r.nextInt(250), 30);
c.setScaleX(currentScale);
c.setScaleY(currentScale);
root.getChildren().add(c);
count++;
if (count > 5){
count = 0;
if (currentScale == scale1){
currentScale = scale2;
} else {
currentScale = scale1;
}
Iterator<Node> iterator = root.getChildren().iterator();
while (iterator.hasNext()) {
Node next = iterator.next();
next.setScaleX(currentScale);
next.setScaleY(currentScale);
}
}
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
The real problem here is that the Group's pivot point -- the relative point for rotation and scaling -- is dependent on the Group's layout-bounds. Therefore, if layout-bounds change, due to adding new children (or existent children changing position, size, or rotation), the relative point for all transformations on the Group changes as well.
In the JavaFX source code, you can find the definition of the pivot point in the Node.java file. The methods impl_getPivotX() and impl_getPivotY() return the center x resp. y coordinate of the layout-bounds.
Unfortunately, there is no option to manually set the pivot point. But as every Node manages a list of additional transformations which are applied on top of the standard transformations, you can easily achieve the desired behaviour:
final Scale scale = new Scale();
group.getTransforms().add(scale);
// change scale
scale.setX(2);
Because you change size of the group after each circle being added, thus triggering relocation of the Group inside the Pane.
You can either:
add circles directly to pane
pane.getChildren().add(new Circle(...
add a large background to fix Group size:
// numbers are huge because you are using 1/5 scaling
Rectangle base = new Rectangle(-10000, -10000, 20000, 20000);
base.setFill(Color.LIGHTGRAY);
root.getChildren().add(base);
I had the same problem drawing a signal which has some values that came out of the bounds.
Use a Pane instead of Group. You use absolute positioning also and it does not move arround its bounds.
Pane JavaFx 8
Use javafx.scene.layout.Pane instead of javafx.scene.Group.

Creating ring shape in Android code

I have the following shape XML:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:a="http://schemas.android.com/apk/res/android"
a:shape="ring"
a:innerRadiusRatio="3"
a:thicknessRatio="8"
a:useLevel="false">
<!-- some other stuff goes here -->
</gradient>
</shape>
I would like to use code instead to create this shape, since some things need to be calculated on the fly before I do it, so static pre-defined layout doesn't cut it.
I'm new to Android and can't quite figure out how XML translates to code, and there's no RingShape class inheriting from Shape.
In addition to answering just this question, if there's a guide somewhere that details relation between XML and Java code and how XML gets processed in order to end up on the screen I would appreciate a link too. Thanks.
Reuben already pointed out most the most useful observations, so I'll just focus on the implementation side of the story. There's multiple approaches using reflection that'll probably give you what you're looking for.
First one is to (ab)use the private GradientDrawable constructor that takes a GradientState reference. Unfortunately the latter is a final subclass with package visibility, so you can't easily get access to it. In order to use it, you would need to dive further in using reflection or mimic its functionality into your own code.
Second approach is to use reflection to get the private member variable mGradientState, which fortunately has a getter in the form of getConstantState(). This'll give you the ConstantState, which at runtime is really a GradientState and hence we can use reflection to access its members and change them at runtime.
In order to support above statements, here's a somewhat basic implementation to create a ring-shaped drawable from code:
RingDrawable.java
public class RingDrawable extends GradientDrawable {
private Class<?> mGradientState;
public RingDrawable() {
this(Orientation.TOP_BOTTOM, null);
}
public RingDrawable(int innerRadius, int thickness, float innerRadiusRatio, float thicknessRatio) {
this(Orientation.TOP_BOTTOM, null, innerRadius, thickness, innerRadiusRatio, thicknessRatio);
}
public RingDrawable(GradientDrawable.Orientation orientation, int[] colors) {
super(orientation, colors);
setShape(RING);
}
public RingDrawable(GradientDrawable.Orientation orientation, int[] colors, int innerRadius, int thickness, float innerRadiusRatio, float thicknessRatio) {
this(orientation, colors);
try {
setInnerRadius(innerRadius);
setThickness(thickness);
setInnerRadiusRatio(innerRadiusRatio);
setThicknessRatio(thicknessRatio);
} catch (Exception e) {
// fail silently - change to your own liking
e.printStackTrace();
}
}
public void setInnerRadius(int radius) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
if (mGradientState == null) mGradientState = resolveGradientState();
Field innerRadius = resolveField(mGradientState, "mInnerRadius");
innerRadius.setInt(getConstantState(), radius);
}
public void setThickness(int thicknessValue) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
if (mGradientState == null) mGradientState = resolveGradientState();
Field thickness = resolveField(mGradientState, "mThickness");
thickness.setInt(getConstantState(), thicknessValue);
}
public void setInnerRadiusRatio(float ratio) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
if (mGradientState == null) mGradientState = resolveGradientState();
Field innerRadiusRatio = resolveField(mGradientState, "mInnerRadiusRatio");
innerRadiusRatio.setFloat(getConstantState(), ratio);
}
public void setThicknessRatio(float ratio) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
if (mGradientState == null) mGradientState = resolveGradientState();
Field thicknessRatio = resolveField(mGradientState, "mThicknessRatio");
thicknessRatio.setFloat(getConstantState(), ratio);
}
private Class<?> resolveGradientState() {
Class<?>[] classes = GradientDrawable.class.getDeclaredClasses();
for (Class<?> singleClass : classes) {
if (singleClass.getSimpleName().equals("GradientState")) return singleClass;
}
throw new RuntimeException("GradientState could not be found in current GradientDrawable implementation");
}
private Field resolveField(Class<?> source, String fieldName) throws SecurityException, NoSuchFieldException {
Field field = source.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
}
}
Above can be used as follows to create a RingDrawable from code and display it in a standard ImageView.
ImageView target = (ImageView) findViewById(R.id.imageview);
RingDrawable ring = new RingDrawable(10, 20, 0, 0);
ring.setColor(Color.BLUE);
target.setImageDrawable(ring);
This will show a simple, opaque blue ring in the ImageView (10 units inner radius, 20 units thick). You'll need to make sure to not set the ImageView's width and height to wrap_content, unless you add ring.setSize(width, height) to above code in order for it to show up.
Hope this helps you out in any way.
Ring and other shapes are GradientDrawables.
If you look at the source code for GradientDrawable, you'll see it looks like certain properties (like innerRadius) can only be defined through XML... they are not exposed through accessor methods. The relevant state is also unhelpfully private to the class, so subclassing is no help either.
You can do something like this:
private ShapeDrawable newRingShapeDrawable(int color) {
ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(color);
drawable.getPaint().setStrokeWidth(2);
drawable.getPaint().setStyle(Paint.Style.STROKE);
return drawable;
}
It is possible to do it from code:
int r = dipToPixels(DEFAULT_CORNER_RADIUS_DIP); // this can be used to make it circle
float[] outerR = new float[]{r, r, r, r, r, r, r, r};
int border = dipToPixels(2); // border of circle
RectF rect = new RectF(border, border, border, border);
RoundRectShape rr = new RoundRectShape(outerR, rect, outerR);// must checkout this constructor
ShapeDrawable drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(badgeColor);// change color of border
// use drawble now
For me it works as follow: (also for Android version > lollipop)
ImageView target = (ImageView) findViewById(R.id.imageview);
GradientDrawable shapeRing = new GradientDrawable();
shapeRing.setShape(GradientDrawable.OVAL);
shapeRing.setColor(centerColor); // transparent
shapeRing.setStroke(stroke, strokeColor);
shapeRing.setSize(width, width);
target.setImageDrawable(ring);

Resources