How to center javafx scene graph "camera" - java

I have a group with two circles on it, when I move one of them with a translate transition I should see the stationary one remain at the center(which is in the middle of the scene graph) and the other one move. Instead what happens is the "camera" follows the moving circle making it seem like they are both moving apart.
Is there a way to center the camera on 0,0 so that it remains there instead of following the circle?
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Test extends Application
{
public static void main(String[] args)
{
launch(args);
}
public void start(Stage stage)
{
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color: Black");
Group graph = new Group();
root.setCenter(graph);
graph.setLayoutX(250);
graph.setLayoutY(250);
Circle circle = new Circle(0,0,5);
circle.setFill(Color.ORANGE);
graph.getChildren().add(circle);
Circle circle2 = new Circle(0, 0, 5);
circle2.setFill(Color.AQUA);
graph.getChildren().add(circle2);
TranslateTransition t = new TranslateTransition(Duration.millis(1000), circle);
t.setFromX(0);
t.setToX(100);
t.setFromY(0);
t.setToY(0);
t.setInterpolator(Interpolator.LINEAR);
t.play();
stage.setTitle("Circle Test");
stage.setScene((new Scene(root, 500, 500)));
stage.show();
}
}

To understand what is happening with the layout here, first note that the layout coordinates of the Group graph are ignored entirely, because you place graph in a layout container (a BorderPane). (Comment out the setLayoutX and setLayoutY lines and you will see they make no difference.) The layout container will size its child nodes according to 1. how much space it has for them, 2. the child nodes' min, preferred, and max sizes. Since the BorderPane doesn't have any other child nodes in this example, it wants to allocate all its available space to the graph. Since graph is in the center, if there is space it cannot allocate to it, it will center it, leaving the rest of the space unused.
Groups behave differently to Regions (which include Controls, Panes, and their subclasses): according to the documentation they are not resizable and take on the collective bounds of their children.
At the beginning of your animation, both circles are coincident, centered at (0,0) and with radius 5: so their bounding boxes (and consequently the bounding box of the Group) has top left corner at (-5,-5) and width and height of 10. This square 10x10 bounding box cannot be made bigger (since it's a Group, which is not resizable), and is centered on the screen. Since the BorderPane has 500 pixels of total width available, there are 490 pixels of unused width, which are divided equally on either side of the Group to center it: 245 to the left and 245 to the right. So the left edge of the Group, which is the left edge of both the circles, is at x=245 in the BorderPane coordinate system.
At the end of the animation, one circle remains at (-5,-5) with width 10x10, while the other has been translated 100 pixels to the right, so its bounding box extends from (95, -5) to (105, 5). Consequently, the bounding box of the Group, which takes on the collective bounds of its child nodes, has top left at (-5, -5), width 110 and height 10. This box cannot be resized, so the BorderPane's layout mechanism centers this box in the area it has available. Since the BorderPane has a width of 500 pixels available, there are 390 unused pixels in width which are divided equally on either side: 195 on the left of the Group and 195 on the right. So at this point, the left edge of the Group, which is the left edge of the untranslated circle, is at x=195 in the BorderPane coordinate system. Consequently, at the end of the animation, the untranslated circle has moved 50 pixels (half of the translation distance) to the left in the BorderPane's coordinate system.
A more natural thing to do here is to use a Pane instead of a Group. A Pane is resizable, so the BorderPane will simply expand it to fill all the available space. Thus it will sit in the top left of the BorderPane and fill the BorderPane. The bounds of the Pane start at (0,0) and extend to its width and height. Thus if you simply change Group to Pane, the untranslated circle will not move during the animation, as you want.
However, the circles will now both start in the top left of the pane instead of the center. If you want them to start in the center, you can change the coordinates of the circles themselves, so they start centered at (250, 250):
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color: Black");
Pane graph = new Pane();
root.setCenter(graph);
// graph.setLayoutX(250);
// graph.setLayoutY(250);
Circle circle = new Circle(250, 250, 5);
circle.setFill(Color.ORANGE);
graph.getChildren().add(circle);
Circle circle2 = new Circle(250, 250, 5);
circle2.setFill(Color.AQUA);
graph.getChildren().add(circle2);
TranslateTransition t = new TranslateTransition(Duration.millis(1000), circle);
t.setFromX(0);
t.setToX(100);
t.setFromY(0);
t.setToY(0);
t.setInterpolator(Interpolator.LINEAR);
t.play();
stage.setTitle("Circle Test");
stage.setScene((new Scene(root, 500, 500)));
stage.show();
}
}
As an alternative, you could use a Pane as the root, instead of a BorderPane. A plain Pane doesn't do any layout, so in this case the layoutX and layoutY settings will take effect. Thus you can revert the centers of the circles to (0,0), and use the layout settings on graph to center it:
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
Pane root = new Pane();
root.setStyle("-fx-background-color: Black");
Pane graph = new Pane();
root.getChildren().add(graph);
graph.setLayoutX(250);
graph.setLayoutY(250);
Circle circle = new Circle(0, 0, 5);
circle.setFill(Color.ORANGE);
graph.getChildren().add(circle);
Circle circle2 = new Circle(0, 0, 5);
circle2.setFill(Color.AQUA);
graph.getChildren().add(circle2);
TranslateTransition t = new TranslateTransition(Duration.millis(1000), circle);
t.setFromX(0);
t.setToX(100);
t.setFromY(0);
t.setToY(0);
t.setInterpolator(Interpolator.LINEAR);
t.play();
stage.setTitle("Circle Test");
stage.setScene((new Scene(root, 500, 500)));
stage.show();
}
}

You can change the class name to whatever you want.
The problem you had was that you added it through the setCenter() method which automatically makes its center the center of the pane.
I hope this came in time.
import javafx.animation.Interpolator;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class NewClass extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
BorderPane root = new BorderPane();
root.setStyle("-fx-background-color: #efefef");
Group graph = new Group();
root.getChildren().add(graph);
graph.setLayoutX(250);
graph.setLayoutY(250);
Circle circle = new Circle(0, 0, 5);
circle.setFill(Color.ORANGE);
graph.getChildren().add(circle);
Circle circle2 = new Circle(0, 0, 5);
circle2.setFill(Color.AQUA);
graph.getChildren().add(circle2);
TranslateTransition t = new TranslateTransition(Duration.millis(1000), circle);
t.setFromX(0);
t.setToX(100);
t.setFromY(0);
t.setToY(0);
t.setInterpolator(Interpolator.LINEAR);
t.setCycleCount(5);
t.play();
stage.setTitle("Circle Test");
stage.setScene((new Scene(root, 500, 500)));
stage.show();
}
}

Related

How to "capture" the event when node moves under the stand still mouse

We know that in JavaFX the MOUSE_MOVED event is fired when the cursor moves on an EventTarget. In this case, the node stands still and the cursor moves.
Now, consider this: We have a ScrollPane and there are some small nodes in it. We let the cursor stay still, and scroll the wheel to scroll the pane. Then a node appears under the cursor. In this case, we will not get the MOUSE_MOVED event while the node passes under the cursor.
For example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class HelloApplication extends Application {
#Override
public void start(Stage stage) {
Circle circle = new Circle(20.0);
Canvas canvas = new Canvas(400, 400); // Make the StackPane large enough
StackPane root = new StackPane();
ScrollPane pane = new ScrollPane();
circle.setFill(Color.RED);
circle.setLayoutX(200);
circle.setLayoutY(200);
canvas.setMouseTransparent(true);
root.getChildren().addAll(circle, canvas);
pane.setContent(root);
circle.setOnMouseEntered(e -> System.out.println("entered"));
circle.setOnMouseMoved(e -> System.out.println("moved"));
circle.setOnMouseExited(e -> System.out.println("exited"));
Scene scene = new Scene(pane, 420, 200);
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
There is a Circle in a ScrollPane. If we let the cursor pass the circle, we will get
entered
moved
moved
...
exited
But if we posit the cursor in the width centre of the scene, above the circle, and use the wheel to scroll to let the circle pass the cursor. We will get
entered
exited
There are no MOUSE_MOVED events.
What I want is to find a type of event that could represent the missing part of the pass-through.

JavaFX: Drawing a infinite symbol and moving along

I need to create a JavaFX application that generates a path in the form of an infinite symbol, and then create a rectangle that will move across that path.
So far I know to create a circle and square and with transitionPath to move that rectangle , but how to create an infinity shape? I'm very fresh in JavaFx (and in development as well) so please don't be harsh :)
Here is my code with Circle shape:
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
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.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class PathTransitionDemo extends Application {
#Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Rectangle rectangle = new Rectangle (0, 0, 25, 50);
rectangle.setFill(Color.ORANGE);
Circle circle = new Circle(125, 100, 50);
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);
pane.getChildren().add(circle);
pane.getChildren().add(rectangle);
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(4000));
pt.setPath(circle);
pt.setNode(rectangle);
pt.setOrientation(
PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
pt.setCycleCount(Timeline.INDEFINITE);
pt.setAutoReverse(true);
pt.play();
circle.setOnMousePressed(e -> pt.pause());
circle.setOnMouseReleased(e -> pt.play());
Scene scene = new Scene(pane, 250, 200);
primaryStage.setTitle("PathTransitionDemo"); // Unos nayiva pozornice e
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I looked everywhere for some hint, but without luck :(
I found on the web an SVG path to draw an "infinity" shape, so replace your circle with:
SVGPath svg = new SVGPath();
svg.setFill(Color.TRANSPARENT);
svg.setStrokeWidth(1.0);
svg.setStroke(Color.BLACK);
svg.setContent("M 787.49,150 C 787.49,203.36 755.56,247.27 712.27,269.5 S 622.17,290.34 582.67,279.16 508.78,246.56 480,223.91 424.93,174.93 400,150 348.85,98.79 320,76.09 256.91,32.03 217.33,20.84 130.62,8.48 87.73,30.5 12.51,96.64 12.51,150 44.44,247.27 87.73,269.5 177.83,290.34 217.33,279.16 291.22,246.56 320,223.91 375.07,174.93 400,150 451.15,98.79 480,76.09 543.09,32.03 582.67,20.84 669.38,8.48 712.27,30.5 787.49,96.64 787.49,150 z");
and use it for drawing, transition and event catching.
You may need to adapt it to your need.
If you are looking for better "infinity" shapes, then search for "lemniscate".

ImageView.getLayoutY() wrong value?

I have a little problem I hope you can help me with:
In this Scene, That blue circle is a 128x128 ImageView, this ImageView is in an HBox, and the HBox is in a VBox, I then set the VBox alignment to Pos.CENTER;
Everything's ok, but when I print the layoutY of the ImageView, it says 0 instead of a 61 (Scene's height is 250, so the layoutY should be 125 - 64);
Does someone have an idea?
Thanks.
The layoutX and layoutY properties determine the layout position of a node within its parent: in this case, the layout position of the image in the HBox. Since there is nothing else in the HBox, the image view will just be at (0,0) in the coordinate system of the HBox, so you will just get 0 for the layoutY property.
(Note also that transforms, such as translations, are applied independently of the layout coordinates - if you like to think of it this way, the node is laid out, then transforms are applied which will alter its final position. So transforms do not modify the layoutX and layoutY properties.)
To get the location of a node in the scene, you can use the localToScene transform to convert a point in the node's own coordinate system to a point in the scene's coordinate system. So to get the location of the top left ((0,0)) of the image view in the scene, you can do
image.localToScene(new Point2D(0, 0))
Here is a complete SSCCE (just using a plain Region to stand in for the image view):
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class BoundsInSceneExample extends Application {
#Override
public void start(Stage primaryStage) {
HBox hbox = new HBox();
Node image = createImage();
hbox.getChildren().add(image);
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.getChildren().add(hbox);
Scene scene = new Scene(root, 250, 250);
// force the layout, so layout computations are performed:
root.layout();
System.out.printf("Layout coordinates: [%.1f, %.1f]%n", image.getLayoutX(), image.getLayoutY());
Point2D sceneCoords = image.localToScene(new Point2D(0,0));
System.out.printf("Scene coordinates: [%.1f, %.1f]%n", sceneCoords.getX(), sceneCoords.getY());
primaryStage.setScene(scene);
primaryStage.show();
}
private Node createImage() {
Region region = new Region();
region.setMinSize(128, 128);
region.setPrefSize(128, 128);
region.setMaxSize(128, 128);
region.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
return region ;
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Layout coordinates: [0.0, 0.0]
Scene coordinates: [0.0, 61.0]

Making More Than One Circle in Java

I have a project in class where I need to display a traffic light with simply three cirlces. I started with the yellow one, and then attempted to add a red one in some random other place just to see if I could do it, however the yellow one is the only one showing. I can't tell if the red one is somehow underneath the yellow one, but in any case it doesn't make much sense to me as to why the red circle isn't showing.
package tryingGraphicsStuff;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.scene.paint.*;
import javafx.scene.text.*;
import javafx.scene.control.*;
public class TryingGraphicsStuff extends Application{
#Override
public void start(Stage stage) throws Exception {
// create circle
Circle circle = new Circle();
circle.setCenterX(150);
circle.setCenterY(150);
circle.setRadius(50);
circle.setFill(Color.RED);
// place on pane
StackPane p = new StackPane();
p.getChildren().add(circle);
// ensure it stays centered if window resized
//circle.centerXProperty().bind(p.widthProperty().divide(2));
//circle.centerYProperty().bind(p.heightProperty().divide(2));
Circle circleTwo = new Circle();
circleTwo.setCenterX(400);
circleTwo.setCenterY(400);
circleTwo.setRadius(50);
circleTwo.setFill(Color.YELLOW);
// place on pane
p.getChildren().add(circleTwo);
// create scene from pane
Scene scene = new Scene(p, 300, 1000);
// place scene on stage
stage.setTitle("Circle");
stage.setScene(scene);
stage.show();
}
public static void main (String [] args)
{
Application.launch(args);
}
}
A StackPane "lays out its children in a back-to-front stack". (The stack here is in z-coordinates). It is a "layout pane" which actually manages the placement of the child nodes for you. Consequently, the centerX and centerY properties of the circles are ignored, and they appear one on top of the other in the order they are added (so the red one is underneath the yellow one, and the only one you see is the yellow one). By default, the stack pane centers them.
All "layout panes" position the nodes for you. For example, a VBox will position nodes in a vertical stack, with the first one at the top, the second below, and so on. So if you used a VBox instead of a StackPane, the circles would appear one below the other (in the y-direction), but note they would still not respect the centerX and centerY properties.
The Pane class itself does not manage the layout of its child nodes; so if you want to use the coordinates for shape objects, Pane is probably your best option. Group behaves similarly, but takes on the bounds of the union of its child bounds, so it acts like Pane but its local coordinate system is different.
The following demo shows all these options. Again, Pane will be the one that behaves in an intuitive way.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class CircleLayoutExample extends Application {
#Override
public void start(Stage primaryStage) {
TabPane tabs = new TabPane();
tabs.getTabs().add(createTab(new StackPane()));
tabs.getTabs().add(createTab(new VBox()));
tabs.getTabs().add(createTab(new Pane()));
tabs.getTabs().add(createTab(new Group()));
Scene scene = new Scene(tabs, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private Tab createTab(Pane pane) {
Circle c1 = new Circle(150, 150, 50, Color.RED);
Circle c2 = new Circle(400, 400, 50, Color.YELLOW);
pane.getChildren().addAll(c1, c2);
Tab tab = new Tab(pane.getClass().getSimpleName());
tab.setContent(pane);
return tab ;
}
// annoyingly, Pane and Group do not have a common superclass with a getChildren()
// method, so just reproduce the code...
private Tab createTab(Group pane) {
Circle c1 = new Circle(150, 150, 50, Color.RED);
Circle c2 = new Circle(400, 400, 50, Color.YELLOW);
pane.getChildren().addAll(c1, c2);
Tab tab = new Tab(pane.getClass().getSimpleName());
tab.setContent(pane);
return tab ;
}
public static void main(String[] args) {
launch(args);
}
}
Yeah your both the circles are overlapping.
You can simply use a VBox instead of StackPane. It will solve your issue.
VBox p = new VBox();
As other answers have suggested, using a VBox would help you out the most here, since it will automatically put its children into a vertical row. Here is a brief snippet using an array (so you can make as many circles as you want)
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Circle;
import javafx.scene.paint.*;
public class TryingGraphicsStuff extends Application{
#Override
public void start(Stage stage) throws Exception {
Circle[] circle = new Circle[3]; // create 3 circles
VBox vBox = new VBox(); // vbox will put circles in vertical row
vBox.setAlignment(Pos.CENTER); // center circles
for(int i = 0; i < circle.length; i++){
circle[i] = new Circle(50); // initialize circles with radius of 50
vBox.getChildren().add(circle[i]);
}
circle[0].setFill(Color.RED);
circle[1].setFill(Color.YELLOW);
circle[2].setFill(Color.GREEN);
// add vbox to scene
Scene scene = new Scene(vBox, 300, 800);
stage.setTitle("Circle");
stage.setScene(scene);
stage.show();
}
public static void main (String [] args){
Application.launch(args);
}
}
As always, please understand the code and don't just mindlessly copy and paste. Cheers!
I'm actually a bit confused by the code above. According to your numbers the red one should be the one showing and not the yellow one. Your scene is only 300px wide and you center the yellow circle at 400 which will put it out of view (having a radius of only 50).
Either increase your scene size or move your circle inside your view.

is it possible to set a javaFX Pane origin to bottom-left?

Is it possible so set the origin of a Pane to the bottom-left corner (instead of top-left)? I'm adding many shapes to my canvas which are defined within the "mathematical coordinate system".
I thought there is perhaps an easier way than always substract the height from the y-coordinate. Another advantage would be that I don't have to take care of resizing the pane.
If all you are doing is using shapes, you can apply a reflection to the pane. You can represent a reflection as a Scale with x=1 and y=-1. The only tricky part is that you must keep the pivot of the scale at the vertical center, which needs a binding in case the pane changes size.
If you're putting controls, or text, in the pane, then those will also be reflected, so they won't look correct. But this will work if all you are doing is using shapes.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
public class ReflectedPaneTest extends Application {
#Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Scale scale = new Scale();
scale.setX(1);
scale.setY(-1);
scale.pivotYProperty().bind(Bindings.createDoubleBinding(() ->
pane.getBoundsInLocal().getMinY() + pane.getBoundsInLocal().getHeight() /2,
pane.boundsInLocalProperty()));
pane.getTransforms().add(scale);
pane.setOnMouseClicked(e ->
System.out.printf("Mouse clicked at [%.1f, %.1f]%n", e.getX(), e.getY()));
primaryStage.setScene(new Scene(pane, 600, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Categories

Resources