Rotate scrollpane over the X-axis in javafx - star wars like effect - java

I have a problem with a rotation of a usercontrol in javafx. My setup is as follows:
I have a scene with in the center a 400 by 600 scrollpanel called scrollpane, later populated dynamically with a vbox that contains a list of labels with text.
What I want to do is add a rotation on this panel to make it look like the starwars introduction text. I've managed to get the animation that scrolls through the text working, but when trying to rotate the panel over the X_AXIS it won't do as I want.
Goal: Panel that is rotated as if it was this text
Currently My best attempt after spending hours transforming:
scrollpane.getTransforms().add(new Rotate(50, 300, 200, 20, Rotate.X_AXIS));
As you can see the text is aimed at the proper angle, but the control itself is not actually 3d rotated over the X-axis.
What do I need to add in order to go from what I currently have to the desired effect?
(That the top of the panel in absolute pixels is less wide compared to the bottom).

You've rotated it backwards; probably you're not seeing the rotation because you have something else wrong in your code.
This works for me:
import javafx.application.Application;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.text.Font;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class StarWarsScrollPane extends Application {
private final String text = "It is a period of civil war. Rebel spaceships, "
+ "striking from a hidden base, have won their first victory against the evil Galactic Empire."
+ " During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon,"
+ " the DEATH STAR, an armored space station with enough power to destroy an entire planet."
+ " Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship,"
+ " custodian of the stolen plans that can save her people and restore freedom to the galaxy....";
#Override
public void start(Stage primaryStage) {
Label label = new Label(text);
label.setWrapText(true);
label.setFont(Font.font(18));
ScrollPane crawler = new ScrollPane(label);
crawler.setVbarPolicy(ScrollBarPolicy.NEVER);
crawler.setFitToWidth(true);
crawler.getTransforms().add(new Rotate(-50, 300, 200, 20, Rotate.X_AXIS));
Scene scene = new Scene(crawler, 400, 400);
scene.setCamera(new PerspectiveCamera());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Note that if you really want a scrolling "crawl" of text, you don't really need a scroll pane, but you can just use a text node and translate it in an animation. If you do this, be sure to add the translation after you add the rotation: transforms are applied in reverse order (as though you are right-multiplying the affine transformation matrices).
Here's an example of this ;)
import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.DepthTest;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Duration;
public class StarWarsCrawler extends Application {
private final String text = "It is a period of civil war. Rebel spaceships, "
+ "striking from a hidden base, have won their first victory against the evil Galactic Empire.\n\n"
+ "During the battle, Rebel spies managed to steal secret plans to the Empire's ultimate weapon,"
+ " the DEATH STAR, an armored space station with enough power to destroy an entire planet.\n\n"
+ "Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship,"
+ " custodian of the stolen plans that can save her people and restore freedom to the galaxy....";
#Override
public void start(Stage primaryStage) {
Rectangle2D primaryScreenBounds = Screen.getPrimary().getBounds();
int width = (int) primaryScreenBounds.getWidth() ;
int height = (int) primaryScreenBounds.getHeight() ;
Text textNode = createText(width);
Translate translate = new Translate();
textNode.getTransforms().add(new Rotate(-60, 300, height/2, height/30, Rotate.X_AXIS));
textNode.getTransforms().add(translate);
Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(45), new KeyValue(translate.yProperty(), -10*height))
);
textNode.setTranslateY(2*height);
StackPane root = new StackPane();
generateStarField(width, height, root);
root.getChildren().add(textNode);
Scene scene = createScene(root);
primaryStage.setFullScreenExitHint("");
primaryStage.setFullScreen(true);
primaryStage.setScene(scene);
primaryStage.show();
animation.play();
animation.setOnFinished(e -> Platform.exit());
}
private Scene createScene(StackPane root) {
Scene scene = new Scene(root, Color.BLACK);
PerspectiveCamera camera = new PerspectiveCamera();
camera.setDepthTest(DepthTest.ENABLE);
scene.setCamera(camera);
scene.setCursor(Cursor.NONE);
scene.setOnMouseClicked(e -> {
if (e.getClickCount() ==2) {
Platform.exit();
}
});
return scene;
}
private Text createText(int width) {
Text textNode = new Text(text);
textNode.setWrappingWidth(width*1.25);
textNode.setFont(Font.font("Franklin Gothic", width/12));
textNode.setFill(Color.rgb(229, 177, 58));
return textNode;
}
private void generateStarField(int width, int height, StackPane root) {
int numStars = width * height / 900 ;
Random rng = new Random();
for (int i = 1 ; i <= numStars ; i++) {
double hue = rng.nextDouble() * 360 ;
double saturation = rng.nextDouble() * 0.1 ;
Color color = Color.hsb(hue, saturation, 1.0);
Circle circle = new Circle(rng.nextInt(width), rng.nextInt(height), 2*rng.nextDouble(), color);
circle.setManaged(false);
circle.setTranslateZ(rng.nextDouble() * height * 1.25);
root.getChildren().add(circle);
}
}
public static void main(String[] args) {
launch(args);
}
}

Related

Getting an input with javaFX

I am trying to use a text field to get an input which represents the radius to draw a circle.
I have tried creating the circle inside processreturn.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class Task5 extends Application {
int rad;
int x = 200;
private TextField input;
public void start(Stage stage) {
input = new TextField();
input.setPrefWidth(50);
input.setAlignment(Pos.CENTER);
input.setOnAction(this::processReturn);
System.out.print(rad);
Circle circle = new Circle();
// Setting the properties of the circle
circle.setCenterX(x);
circle.setCenterY(200);
circle.setRadius(rad);
// Creating a Group object
Group root = new Group(circle, input);
// Creating a scene object
Scene scene = new Scene(root, 600, 300, Color.LIGHTBLUE);
// Setting title to the Stage
stage.setTitle("Drawing a Circle");
// Adding scene to the stage
stage.setScene(scene);
// Displaying the contents of the stage
stage.show();
System.out.print(rad);
}
public void processReturn(ActionEvent event) {
rad = Integer.parseInt(input.getText());
System.out.println("rad is" + rad);
}
}
Currently it seems that the variable rad is changing but it is not updating the circle in the Group instance. Is it possible to update the group or create another group that has a the circle with the updated rad?

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".

How to center javafx scene graph "camera"

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();
}
}

Changing an Int value to a String in object oriented programming

I am making a simple game on JavaFX right now.
The picture of my program is here
So far, my code is generating random monsters using a random number generator, and my health will decrease a random number each time I hit the explore button.
I also added a stats box. This box will display my current health, hunger, and hydration levels.
My problem is, is that I am not sure how I am supposed to change the values in my stats box. Every time my character gets hit by a monster, I want the health text to change. When I do :
dStatBox.setText(mainCharacter.getHealthLevel());
It says that I must convert the int to a string. How can I go about doing this?
My whole code is below:
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class Game extends Application {
public static TextArea dialogue = new TextArea();
public static TextArea dStatBox = new TextArea();
Button exploreButton;
Random r = new Random();
int ogreDamage = r.nextInt(20) + 1;
public void start(Stage primaryStage) {
Character mainCharacter = new Character("Nikki");
BorderPane pane = new BorderPane();
HBox top = new HBox();
VBox gameBox = new VBox();
VBox explore = new VBox();
VBox statBox = new VBox();
exploreButton = new Button("Explore");
Label stats = new Label("Stats");
stats.setFont(Font.font(30));
stats.setFont(Font.font("Helvetica", FontWeight.BOLD, FontPosture.REGULAR, 24));
statBox.setPadding(new Insets(10,10,10,10));
statBox.setSpacing(10);
statBox.setMaxHeight(300);
statBox.setPrefWidth(300);
statBox.getChildren().addAll(stats, dStatBox);
statBox.setAlignment(Pos.TOP_CENTER);
dStatBox.setEditable(false);
dStatBox.setText("Health: 100/100\n");
Label label = new Label("Game Dialogue");
label.setFont(Font.font(30));
label.setFont(Font.font("Helvetica", FontWeight.BOLD, FontPosture.REGULAR, 24));
gameBox.setPadding(new Insets(10,10,10,10));
gameBox.setSpacing(10);
dialogue.setMaxHeight(200);
dialogue.setMaxWidth(470);
dialogue.setWrapText(true);
dialogue.setEditable(false);
gameBox.getChildren().addAll(label, dialogue, exploreButton);
gameBox.setAlignment(Pos.CENTER);
top.getChildren().addAll(gameBox, statBox);
top.setAlignment(Pos.TOP_LEFT);
pane.setTop(top);
dialogue.appendText("Welcome to Wild Berries - the Ultimate Survival Game\n");
dialogue.appendText("How long can you survive for? Only time will tell...\n");
exploreButton.setOnAction(e -> {
Random r = new Random();
int ogreDamage = r.nextInt(20) + 1;
int randomInt = r.nextInt(3) + 1;
dialogue.appendText("You begin to explore the wild...\n");
if(randomInt == 1) {
dialogue.appendText("A wild Ogre has appeared!\n");
dialogue.appendText("You have been hurt. -" + ogreDamage + " HP.\n");
mainCharacter.setHealthLevel(mainCharacter.getHealthLevel() - ogreDamage);
dialogue.appendText(mainCharacter.getHealthLevel());
if(mainCharacter.getHealthLevel() <= 0) {
dialogue.appendText("You have died. Thank you for playing.");
}
}
if(randomInt == 2) {
dialogue.appendText("A wild Goblin has appeared!\n");
}
if(randomInt == 3) {
dialogue.appendText("A wild Ghost has appeared!\n");
}
});
Scene scene = new Scene(pane, 800, 450);
primaryStage.setScene(scene);
primaryStage.setTitle("Wild Berries GUI");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
I'm assuming that mainCharacter.getHealthLevel() is returning an int. You should do dStatBox.setText("Health: " + mainCharacter.getHealthLevel());
As simple as this:
int healthLevel = mainCharacter.getHealthLevel();
String.valueOf(healthLevel);
//or
Integer.toString(healthLevel);

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.

Categories

Resources