How to play pathtransitions in sequence? - javafx

Is there a special way (some kind of event/transition queue?) in JavaFX with which you can play animations/transitions in sequence?
In a solitaire game at the end the cards are usually already in sequence (K->-Q->J-10->-9->...) and I want to finish them automatically. So first card 9 has to move from the tableau to the foundation, then 10, then J, etc.
I'd like to do the path transition in a transition queue, rather than all at once.
I can't use a SequentialTranstition because you can't modify its children once the animation plays.
public final ObservableList getChildren()
A list of Animations that will be played sequentially.
It is not possible to change the children of a running
SequentialTransition. If the children are changed for a running
SequentialTransition, the animation has to be stopped and started
again to pick up the new value.
Verifiable with this minimal example:
public class PathTransitionDemo extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Group root = new Group();
List<Rectangle> rectangles = new ArrayList<>();
double w = 50;
double h = 50;
double spacing = 10;
for( int i=0; i < 10; i++) {
Rectangle rectangle = new Rectangle ( spacing * (i+1) + w * i, 50, w, h);
rectangle.setStroke( Color.BLUE);
rectangle.setFill( Color.BLUE.deriveColor(1, 1, 1, 0.2));
rectangles.add( rectangle);
}
root.getChildren().addAll( rectangles);
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();
// transition
SequentialTransition seq = new SequentialTransition();
for( Rectangle rectangle: rectangles) {
Path path = new Path();
path.getElements().add (new MoveTo ( rectangle.getX(), rectangle.getY()));
path.getElements().add (new LineTo( 900, 600));
PathTransition pathTransition = new PathTransition();
pathTransition.setDuration(Duration.millis(1000));
pathTransition.setNode(rectangle);
pathTransition.setPath(path);
//pathTransition.play();
seq.getChildren().add( pathTransition);
if( seq.getStatus() != Status.RUNNING)
seq.play();
}
// seq.play();
}
}
The sequential transition stops after it played the first path transition.
A solution would be to modfiy the setOnFinished handler of the PathTransitions. But that's ugly. And it plays only exaclty 1 transtition after the other. Let's say one card transition lasts 2000 ms, it e. g. limits the possibility to start another transition of the queue within 500ms.
The animation in the Video Wall that I created has a similar requirement. There I solved it with an AnimationTimer. Excerpt from the code:
AnimationTimer timer = new AnimationTimer() {
long last = 0;
#Override
public void handle(long now) {
if( (now - last) > 40_000_000)
{
if( transitionList.size() > 0) {
ParallelTransition t = transitionList.remove(0);
t.getNode().setVisible(true);
t.play();
}
last = now;
}
if( transitionList.size() == 0) {
stop();
}
}
};
Is there a better way to solve this in JavaFX?
Thank you very much!

Related

FlowPane automatic horizontal space

I have a FlowPane with equally-sized rectangular children and I have this problem with the space at the right end of the flowpane, when the space is not enough to fit another column of children, I want it to be equally divided between the other columns.
An example of what I want to achieve is how the file explorer in windows behaves, see the gif bellow for reference
The default FlowPane behaviour doesn't look like this, it leaves the remaining width that can't fit a new child at the end of the region, as shown in the gif bellow
And I failed to find any API or documentation to help me achieve my goal, I thought of adding a listener on the width property and adjusting the hGap property accordingly, something like
[ flowPaneWidth - (sum of the widths of the children in one column) ] / (column count - 1)
But again, I have no idea how to figure out the column count, so any help would be appreciated.
Here is a MRE if anyone wants to try their ideas :
public class FPAutoSpace extends Application {
#Override
public void start(Stage ps) throws Exception {
FlowPane root = new FlowPane(10, 10);
root.setPadding(new Insets(10));
for(int i = 0; i < 20; i++) {
root.getChildren().add(new Rectangle(100, 100, Color.GRAY));
}
ps.setScene(new Scene(root, 600, 600));
ps.show();
}
}
After a bit of thinking, I tried to implement the idea mentioned in the question :
adding a listener on the width property and adjusting the hGap property accordingly
but I added the listener on the needsLayout property instead, as follows :
public class FPAutoSpace extends Application {
private double nodeWidth = 100;
#Override
public void start(Stage ps) throws Exception {
FlowPane root = new FlowPane();
root.setVgap(10);
for (int i = 0; i < 20; i++) {
root.getChildren().add(new Rectangle(nodeWidth, nodeWidth, Color.GRAY));
}
root.needsLayoutProperty().addListener((obs, ov, nv) -> {
int colCount = (int) (root.getWidth() / nodeWidth);
//added 4 pixels because it gets glitchy otherwise
double occupiedWidth = nodeWidth * colCount + 4;
double hGap = (root.getWidth() - occupiedWidth) / (colCount - 1);
root.setHgap(hGap);
});
StackPane preRoot = new StackPane(root);
preRoot.setPadding(new Insets(10));
preRoot.setAlignment(Pos.TOP_LEFT);
ps.setScene(new Scene(preRoot, 600, 600));
ps.show();
}
}
Not sure how this will hold up in a multi-hundred node FlowPane but it worked for the MRE
Let me know if you think there are better ways to do it.

How to add an ImagePattern to a Rectangle while still maintaining the Rectangles background color

I have a chess board and I am trying to add pieces to the board. Every spot on the board is a Rectangle so I thought the best way to add pieces would be to add an ImagePattern to each Rectangle that gets a piece. The problem I encountered was when I added an ImagePattern to a Rectangle it would make the background of that Rectangle white despite what the color was before the ImagePattern was added. So my question is, is there a way for me to preserve the background color of a Rectangle after an ImagePattern is added?
For demo purposes my code only adds one piece to the board.
public class ChessBoard extends Application {
GridPane root = new GridPane();
final int size = 8;
public void start(Stage primaryStage) {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
Rectangle square = new Rectangle();
Color color;
if ((row + col) % 2 == 0)
color = Color.WHITE;
else
color = Color.BLACK;
square.setFill(color);
root.add(square, col, row);
if(row == 4 && col == 3){
Image p = new Image("Peices/Black/0.png");
ImagePattern pat = new ImagePattern(p);
square.setFill(pat);
}
square.widthProperty().bind(root.widthProperty().divide(size));
square.heightProperty().bind(root.heightProperty().divide(size));
square.setOnMouseClicked(e->{
square.setFill(Color.BLUE);
});
}
}
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I think you are searching for blending which is done with the BlendMode. For example:
Image p = new Image("Peices/Black/0.png");
ImagePattern pat = new ImagePattern(p);
Rectangle r1 = new Rectangle();
r1.setX(50);
r1.setY(50);
r1.setWidth(50);
r1.setHeight(50);
r1.setFill(pat);
Rectangle r = new Rectangle();
r.setX(50);
r.setY(50);
r.setWidth(50);
r.setHeight(50);
r.setFill(Color.BLUE);
r.setBlendMode(BlendMode.ADD);
As far as I know there is no direct way to accomplish this.
Source: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/effect/BlendMode.html
No, you cannot use more than a single fill with a Rectangle. Theoretically you could use a Region with multiple backgrounds, but this is probably a bad idea. Most likely you'll want at least some of the following functionality for the pieces, which will not work, if you do not make pieces their own nodes:
Dragging a piece from one field to another
animating moves
I recommend using a StackPane and put the Board in the background and put a Pane on top of it to place the pieces. Simply use ImageViews for the pieces.
Example:
#Override
public void start(Stage primaryStage) {
GridPane board = new GridPane();
Region[][] fields = new Region[8][8];
for (int i = 0; i < fields.length; i++) {
Region[] flds = fields[i];
for (int j = 0; j < flds.length; j++) {
Region field = new Region();
flds[j] = field;
field.setBackground(new Background(new BackgroundFill((i + j) % 2 == 0 ? Color.WHITE : Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY)));
}
board.addRow(i, flds);
}
// use 1/8 of the size of the Grid for each field
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setPercentHeight(100d / 8);
ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setPercentWidth(100d / 8);
for (int i = 0; i < 8; i++) {
board.getColumnConstraints().add(columnConstraints);
board.getRowConstraints().add(rowConstraints);
}
Pane piecePane = new Pane();
StackPane root = new StackPane(board, piecePane);
NumberBinding boardSize = Bindings.min(root.widthProperty(), root.heightProperty());
ImageView queen = new ImageView("https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Chess_qdt45.svg/480px-Chess_qdt45.svg.png");
DropShadow shadow = new DropShadow(BlurType.GAUSSIAN, Color.WHITE, 2, 1, 0, 0);
// drop shadow for black piece on black field
queen.setEffect(shadow);
// trigger move to topleft field on mouse click
queen.setOnMouseClicked(evt -> {
Node source = (Node) evt.getSource();
TranslateTransition animation = new TranslateTransition(Duration.seconds(0.5), source);
Region targetRegion = fields[0][0];
final PositionChangeListener listener = (PositionChangeListener) source.getUserData();
listener.setField(null);
animation.setByX(targetRegion.getLayoutX() - source.getLayoutX());
animation.setByY(targetRegion.getLayoutY() - source.getLayoutY());
animation.setOnFinished(e -> {
source.setTranslateX(0);
source.setTranslateY(0);
listener.setField(targetRegion);
});
animation.play();
});
PositionChangeListener changeListener = new PositionChangeListener(queen);
queen.setUserData(changeListener);
changeListener.setField(fields[4][3]);
// board size should be as large as possible but at most the min of the parent sizes
board.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE);
board.maxWidthProperty().bind(boardSize);
board.maxHeightProperty().bind(boardSize);
// same size for piecePane
piecePane.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE);
piecePane.maxWidthProperty().bind(boardSize);
piecePane.maxHeightProperty().bind(boardSize);
// add piece to piecePane
piecePane.getChildren().add(queen);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private static class PositionChangeListener implements ChangeListener<Bounds> {
private final ImageView piece;
public PositionChangeListener(ImageView piece) {
this.piece = piece;
}
private Region currentField;
public void setField(Region newRegion) {
// register/unregister listeners to bounds changes of associated field
if (currentField != null) {
currentField.boundsInParentProperty().removeListener(this);
}
currentField = newRegion;
if (newRegion != null) {
newRegion.boundsInParentProperty().addListener(this);
changed(null, null, newRegion.getBoundsInParent());
}
}
#Override
public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) {
// align piece with field
piece.setLayoutX(newValue.getMinX());
piece.setLayoutY(newValue.getMinY());
piece.setFitHeight(newValue.getHeight());
piece.setFitWidth(newValue.getWidth());
}
}

JavaFx Determining whether a mouse is clicking on the background or a Circle

I am creating a game where circles fall from the top of the screen to the bottom. When the circle is clicked its suppose to re-spawn in a random position on top of the screen and with a random color. I am pretty sure my problem has to do with my line to determine if the mouse click was on one of the circles or not is working correctly. So my questions are how would I determine if a mouse click happened on one of the circles or on the background screen? and What is wrong with the following line? (Because I am almost certain that my problem is from that line)
if((shape.get(i).getLayoutX() == e.getX())&&(shape.get(i).getLayoutY() == e.getY())){
My entire code is here:
public class ShapesWindow extends Application{
final int WIDTH = 640;
final int HEIGHT = WIDTH / 12 * 9;
Random r = new Random();
Circle circle;
double yCord;
long startNanoTime;
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT);
Canvas can = new Canvas(WIDTH,HEIGHT);
GraphicsContext gc = can.getGraphicsContext2D();
ArrayList<Shape> shape = new ArrayList<>();
#Override
public void start(Stage theStage) throws Exception {
theStage.setTitle("Click the bubbles!");
theStage.setScene(scene);
root.getChildren().add(can);
gc.setFill(Color.LIGHTBLUE);
gc.fillRect(0,0,WIDTH,HEIGHT);
/* This adds 10 circles to my Group */
for(int i = 0; i < 10; i++){
gc.setFill(Color.LIGHTBLUE);
gc.fillRect(0,0,WIDTH,HEIGHT);
circle = new Circle(15,randomColor());
root.getChildren().add(circle);
circle.setLayoutX(r.nextInt(WIDTH+15));
circle.setLayoutY(0);
shape.add(circle);
}
/* This my attempt at trying to handle the Mouse Events for each thing */
for(int i = 0; i < 10; i++){
shape.get(i).setOnMouseClicked(
new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
shapeClicked(e);
}
});
}
startNanoTime = System.nanoTime();
new AnimationTimer(){
public void handle(long currentNanoTime){
double t = (currentNanoTime - startNanoTime) / 1000000000.0;
yCord = t*20;
for(int i = 0; i < 10; i++){
/* This if statment allows nodes to wrap around from bottom to top */
if(yCord >=HEIGHT){
shape.get(i).setLayoutX(r.nextInt(WIDTH+15));
shape.get(i).setLayoutY(0);
shape.get(i).setFill(randomColor());
resetNan();
}
shape.get(i).setLayoutY(yCord);
}
}
}.start();
theStage.show();
}
/*
* This Function is suppose the change the color and position of the circle that was clicked
*/
public void shapeClicked(MouseEvent e){
for(int i = 0; i < shape.size();i++){
if((shape.get(i).getLayoutX() == e.getX())&&(shape.get(i).getLayoutY() == e.getY())){
shape.get(i).setLayoutX(r.nextInt(WIDTH+15));
shape.get(i).setLayoutY(0);
shape.get(i).setFill(randomColor());
}
}
/*
* This allows the value of startNanoTime to be indrectly change it can not be changed diretly
* inside of handle() inside of the Animation class
*/
public void resetNan(){
startNanoTime = System.nanoTime();
}
public Color randomColor(){
double R = r.nextDouble();
double G = r.nextDouble();
double B = r.nextDouble();
double opacity = .6;
Color color = new Color(R, G, B, opacity);
return color.brighter();
}
public static void main(String[] args){
launch(args);
}
}
Why not just
for(int i = 0; i < 10; i++){
Shape s = shape.get(i);
s.setOnMouseClicked(
new EventHandler<MouseEvent>(){
public void handle(MouseEvent e){
s.setLayoutX(r.nextInt(WIDTH+15));
s.setLayoutY(0);
s.setFill(randomColor());
}
});
}
I know long time passed by, but if anyone else need to check if a mouse click event was on a Circle or any other shape it is better to use the built in .contains method. Thanks to Point2D from JavaFx geometry class you can check if a click (x,y coordinate) is on a shape or not, you don't have to worry about the click position: in the center or border.
for (Circle circle:listOfCircles) {
Point2D point2D = new Point2D(event.getX(),event.getY());
if (circle.contains(point2D)){
System.out.println("circle clicked");
}
}

Create a path transition with absolute coordinates for a StackPane object

OrangeBlock is an orange block with text inside. It is implemented as a StackPane that contains text on top of a rectangle. (This approach is demonstrated in the documentation for StackPane.)
I've placed an OrangeBlock at coordinates (100, 80) and am now trying to make it travel smoothly to some target coordinates. Unfortunately I get a nasty bump in my path:
For some reason the coordinates in the PathElements are interpreted relative to the orange block.
Why is this? And how can I make my OrangeBlock travel along a path with absolute coordinates? Minimal working example below.
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PathTransitionExample extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
OrangeBlock block = new OrangeBlock(60, 40);
block.relocate(100, 80);
root.getChildren().add(block);
PathTransition transition = newPathTransitionTo(block, 460, 320);
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
transition.play();
}
private static PathTransition newPathTransitionTo(OrangeBlock block,
double toX, double toY) {
double fromX = block.getLayoutX();
double fromY = block.getLayoutY();
Path path = new Path();
path.getElements().add(new MoveTo(fromX, fromY));
path.getElements().add(new LineTo(toX, toY));
PathTransition transition = new PathTransition();
transition.setPath(path);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
return transition;
}
public static void main(String[] args) {
launch(args);
}
private static class OrangeBlock extends StackPane {
public OrangeBlock(int width, int height) {
Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
Text text = new Text("Block");
getChildren().addAll(rectangle, text);
}
}
}
I debugged the JavaFX code out of curiosity. Seems like you are out of luck with a proper solution. Here's what happens:
The PathTransition code has a method interpolate(double frac) which includes:
cachedNode.setTranslateX(x - cachedNode.impl_getPivotX());
cachedNode.setTranslateY(y - cachedNode.impl_getPivotY());
The impl_getPivotX() and impl_getPivotY() methods contain this:
public final double impl_getPivotX() {
final Bounds bounds = getLayoutBounds();
return bounds.getMinX() + bounds.getWidth()/2;
}
public final double impl_getPivotY() {
final Bounds bounds = getLayoutBounds();
return bounds.getMinY() + bounds.getHeight()/2;
}
So the PathTransition always uses the center of your node for the calculation. In other words this works with e. g. a Circle node, but not with e. g. a Rectangle node. Moreover you need the layoutBounds, so the PathTransition must be created after the bounds were made available.
You can see in the PathTransition code that the calculations are all relative and already involve the layout position. So in your lineTo you have to consider this.
Worth noting is that the LineTo class has a method setAbsolut(boolean). However it doesn't solve your problem.
So my solution to your problem would be
creating the PathTransition after the primary stage was made visible
modification of the moveTo and lineTo parameters
This works for me (I added a Rectangle shape to identify the proper bounds visually):
public class PathTransitionExampleWorking2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Rectangle rect = new Rectangle( 100, 80, 460-100+60, 320-80+40);
root.getChildren().add(rect);
OrangeBlock block = new OrangeBlock(60, 40);
block.relocate( 100, 80);
root.getChildren().add(block);
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
// layout bounds are used in path transition => PathTransition creation must happen when they are available
PathTransition transition = newPathTransitionTo(block, 460, 320);
transition.play();
}
private static PathTransition newPathTransitionTo(OrangeBlock block, double toX, double toY) {
double fromX = block.getLayoutBounds().getWidth() / 2;
double fromY = block.getLayoutBounds().getHeight() / 2;
toX -= block.getLayoutX() - block.getLayoutBounds().getWidth() / 2;
toY -= block.getLayoutY() - block.getLayoutBounds().getHeight() / 2;
Path path = new Path();
path.getElements().add(new MoveTo(fromX, fromY));
path.getElements().add(new LineTo(toX, toY));
PathTransition transition = new PathTransition();
transition.setPath(path);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
return transition;
}
public static void main(String[] args) {
launch(args);
}
private static class OrangeBlock extends StackPane {
public OrangeBlock(int width, int height) {
Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
Text text = new Text("Block");
getChildren().addAll(rectangle, text);
}
}
}
edit: another solution would be to use this instead of MoveTo and LineTo:
public static class MoveToAbs extends MoveTo {
public MoveToAbs( Node node) {
super( node.getLayoutBounds().getWidth() / 2, node.getLayoutBounds().getHeight() / 2);
}
}
public static class LineToAbs extends LineTo {
public LineToAbs( Node node, double x, double y) {
super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
}
}
Note: You still have to create the PathTransition after the primaryStage was created.
edit: here's another example with the block moving to the position of the mouse-click:
public class PathTransitionExample extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
OrangeBlock block = new OrangeBlock(60, 40);
block.relocate(100, 80);
root.getChildren().add(block);
Label label = new Label( "Click on scene to set destination");
label.relocate(0, 0);
root.getChildren().add(label);
Scene scene = new Scene(root, 600, 400);
scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
PathTransition transition;
{
transition = new PathTransition();
transition.setNode(block);
transition.setDuration(Duration.seconds(2));
}
#Override
public void handle(Event event) {
transition.stop();
setPositionFixed(block.getLayoutX() + block.getTranslateX(), block.getLayoutY() + block.getTranslateY());
double x = ((MouseEvent) event).getX();
double y = ((MouseEvent) event).getY();
Path path = new Path();
path.getElements().add(new MoveToAbs( block));
path.getElements().add(new LineToAbs( block, x, y));
transition.setPath(path);
transition.play();
}
private void setPositionFixed( double x, double y) {
block.relocate(x, y);
block.setTranslateX(0);
block.setTranslateY(0);
}
});
primaryStage.setScene( scene);
primaryStage.show();
PathTransition transition = newPathTransitionTo(block, 460, 320);
transition.play();
}
private static PathTransition newPathTransitionTo(OrangeBlock block, double toX, double toY) {
Path path = new Path();
path.getElements().add(new MoveToAbs( block));
path.getElements().add(new LineToAbs( block, toX, toY));
PathTransition transition = new PathTransition();
transition.setPath(path);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
return transition;
}
public static void main(String[] args) {
launch(args);
}
private static class OrangeBlock extends StackPane {
public OrangeBlock(int width, int height) {
Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
Text text = new Text("Block");
getChildren().addAll(rectangle, text);
}
}
public static class MoveToAbs extends MoveTo {
public MoveToAbs( Node node) {
super( node.getLayoutBounds().getWidth() / 2, node.getLayoutBounds().getHeight() / 2);
}
}
public static class LineToAbs extends LineTo {
public LineToAbs( Node node, double x, double y) {
super( x - node.getLayoutX() + node.getLayoutBounds().getWidth() / 2, y - node.getLayoutY() + node.getLayoutBounds().getHeight() / 2);
}
}
}
The solution I'm using now is to simply offset layoutX and layoutY of the Path in the opposite direction.
private static void offsetPathForAbsoluteCoords(Path path, OrangeBlock block) {
Node rectangle = block.getChildren().iterator().next();
double width = rectangle.getLayoutBounds().getWidth();
double height = rectangle.getLayoutBounds().getHeight();
path.setLayoutX(-block.getLayoutX() + width / 2);
path.setLayoutY(-block.getLayoutY() + height / 2);
}
Inserting a call to this method immediately after the Path instantiation fixes the problem.
I'm not really satisfied with this solution. I don't understand why layoutX and layoutY need to be involved at all. Is there a neater way?
So Basically,
the relocate(x,y) method sets the layout x/y values...
the Transition uses the translateX/Y values...
I could be wrong but I believe that when either value gets invalidated the scene runs a "layout" pass on the nodes in scene.
When this happens it tries to set the node to it's known layoutX/Y values, which are set when you call relocate(x,y) (layout values are 0,0 by default).
This causes the node to be drawn in "layoutPosition" then "pathPosition" within the transition at each step, causing jitters and the node to be offset from where it should be.
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
OrangeBlock block = new OrangeBlock(60, 40);
System.out.println(block.getLayoutX() + " : " + block.getLayoutY());
block.relocate(100, 80);
//block.setTranslateX(100);
//block.setTranslateY(80);
System.out.println(block.getLayoutX() + " : " + block.getLayoutY());
root.getChildren().add(block);
PathTransition transition = newPathTransitionTo(block, 460, 320);
transition.currentTimeProperty().addListener(e->{
System.out.println("\nLayout Values: " + block.getLayoutX() + " : " + block.getLayoutY()
+"\nTranslate Values:" + block.getTranslateX() + " : " + block.getTranslateY()
);});
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
transition.play();
}
private static PathTransition newPathTransitionTo(OrangeBlock block,
double toX, double toY) {
double fromX = block.getLayoutX();//getTranslateX();
double fromY = block.getLayoutY();//getTranslateY();
Path path = new Path();
path.getElements().add(new MoveTo(fromX, fromY));
path.getElements().add(new LineTo(toX, toY));
PathTransition transition = new PathTransition();
transition.setPath(path);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
return transition;
}
public static void main(String[] args) {
launch(args);
}
private static class OrangeBlock extends StackPane {
public OrangeBlock(int width, int height) {
Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
Text text = new Text("Block");
getChildren().addAll(rectangle, text);
}
}
Not going to post pics, But my first result was like your first post, changing it to the above code gave me the second post result.
Usually it is always best to avoid "layout" values on a dynamic (moving) object for these reasons. If you like the convenience of the relocate method, I'd implement your own setting the translate values instead.
Cheers :)
EDIT:
I edited some code to print what happens as the transition is running so you can see what happens in your original version..
Both #jdub1581 and #Lorand have given valid points:
Transition is applied modifying block's translateXProperty() and translateYProperty().
Transition is applied on the center of the block.
I'll add one more thing:
We are mixing two different things: the global path we want the block to follow, and the local path we have to apply to the transition, so the block follows the first one.
Let's add a pathScene to the group:
Path pathScene = new Path();
pathScene.getElements().add(new MoveTo( block.getLayoutX(), block.getLayoutY()));
pathScene.getElements().add(new LineTo(460, 320));
root.getChildren().add(pathScene);
This will be our scene now (I've added two labels with the coordinates of the origin and end of the path for clarity):
Now we need to determine the local path, so we'll change pathScene elements to local coordinates of the block, and translate it to its center:
Path pathLocal = new Path();
pathScene.getElements().forEach(elem->{
if(elem instanceof MoveTo){
Point2D m = block.sceneToLocal(((MoveTo)elem).getX(),((MoveTo)elem).getY());
Point2D mc = new Point2D(m.getX()+block.getWidth()/2d,m.getY()+block.getHeight()/2d);
pathLocal.getElements().add(new MoveTo(mc.getX(),mc.getY()));
} else if(elem instanceof LineTo){
Point2D l = block.sceneToLocal(((LineTo)elem).getX(),((LineTo)elem).getY());
Point2D lc = new Point2D(l.getX()+block.getWidth()/2d,l.getY()+block.getHeight()/2d);
pathLocal.getElements().add(new LineTo(lc.getX(),lc.getY()));
}
});
As #Lorand also mentioned, this should be done after the stage is shown to compute the size of the block.
Now we can create the transition and play it.
PathTransition transition = new PathTransition();
transition.setPath(pathLocal);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
transition.play();
Finally, this is all the code we need to make the block follow the desired path:
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
OrangeBlock block = new OrangeBlock(60, 40);
block.relocate(100, 80);
root.getChildren().add(block);
// Path in scene coordinates, added to group
// in order to visualize the transition path for the block to follow
Path pathScene = new Path();
pathScene.getElements().add(new MoveTo(block.getLayoutX(), block.getLayoutY()));
pathScene.getElements().add(new LineTo(460, 320));
root.getChildren().add(pathScene);
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
PathTransition transition = newPathTransitionTo(pathScene, block);
transition.play();
}
private PathTransition newPathTransitionTo(Path pathScene, OrangeBlock block) {
// Calculate the path in local coordinates of the block
// so transition is applied to the block without bumps
Path pathLocal = new Path();
pathScene.getElements().forEach(elem->{
if(elem instanceof MoveTo){
Point2D m = block.sceneToLocal(((MoveTo)elem).getX(),((MoveTo)elem).getY());
Point2D mc = new Point2D(m.getX()+block.getWidth()/2d,m.getY()+block.getHeight()/2d);
pathLocal.getElements().add(new MoveTo(mc.getX(),mc.getY()));
} else if(elem instanceof LineTo){
Point2D l = block.sceneToLocal(((LineTo)elem).getX(),((LineTo)elem).getY());
Point2D lc = new Point2D(l.getX()+block.getWidth()/2d,l.getY()+block.getHeight()/2d);
pathLocal.getElements().add(new LineTo(lc.getX(),lc.getY()));
}
});
PathTransition transition = new PathTransition();
transition.setPath(pathLocal);
transition.setNode(block);
transition.setDelay(Duration.seconds(1));
transition.setDuration(Duration.seconds(2));
return transition;
}
public static void main(String[] args) {
launch(args);
}
private static class OrangeBlock extends StackPane {
public OrangeBlock(int width, int height) {
Rectangle rectangle = new Rectangle(width, height, Color.ORANGE);
Text text = new Text("Block");
getChildren().addAll(rectangle, text);
}
}
Note that this solution is equivalent to the one given by #Lorand.
If we monitorize the X, Y translate properties of the block, these go from (0,0) to (360,240), which are just the relative ones on the global path.
You're using relocate function to locate your Block. relocate function makes computation on x and y for locating your object. If you used setLayoutX to locate Block and then use getLayoutX, this problem might not be happened. Same explanations is valid for y property.
You can find some informations about your problem in here: http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#layoutXProperty

How to create dynamically Resizable shapes in javafx?

I have three problems:
I want to create resizable shapes with box bounding...
I also want to know how to get child seleted in a Pane.
I'm creating multiple shapes on a pane. I want to change some property of that shape say Fill.. How do i do it??
Thanx
Next example will answer your questions:
for (1) it uses binding, connecting pane size with rectangle size
for (2) it adds setOnMouseClick for each rectangle which stores clicked one in the lastOne field.
for (3) see code of setOnMouseClick() handler
public class RectangleGrid extends Application {
private Rectangle lastOne;
public void start(Stage stage) throws Exception {
Pane root = new Pane();
int grid_x = 7; //number of rows
int grid_y = 7; //number of columns
// this binding will find out which parameter is smaller: height or width
NumberBinding rectsAreaSize = Bindings.min(root.heightProperty(), root.widthProperty());
for (int x = 0; x < grid_x; x++) {
for (int y = 0; y < grid_y; y++) {
Rectangle rectangle = new Rectangle();
rectangle.setStroke(Color.WHITE);
rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
if (lastOne != null) {
lastOne.setFill(Color.BLACK);
}
// remembering clicks
lastOne = (Rectangle) t.getSource();
// updating fill
lastOne.setFill(Color.RED);
}
});
// here we position rects (this depends on pane size as well)
rectangle.xProperty().bind(rectsAreaSize.multiply(x).divide(grid_x));
rectangle.yProperty().bind(rectsAreaSize.multiply(y).divide(grid_y));
// here we bind rectangle size to pane size
rectangle.heightProperty().bind(rectsAreaSize.divide(grid_x));
rectangle.widthProperty().bind(rectangle.heightProperty());
root.getChildren().add(rectangle);
}
}
stage.setScene(new Scene(root, 500, 500));
stage.show();
}
public static void main(String[] args) { launch(); }
}

Resources