When to use translate and when relocate - What is the difference between translate and layout coordinates? - javafx-2

When to use translate and when relocate in order to move a node? In the end of the day it seems they do the same thing (visually); move the node; the first by doing a translation on the origin (the x, y stays the same), the second by changing the x, y coords.
So suppose i want to move a node in a specific point in the screen.. should i use node.relocate(x,y) or node.setTranslateX(x), node.setTranslateY(y)?
To demostrate what I mean I have made a sample program you can play with:
A rectangle on the screen, whose position is determined by 4 sliders (2 of them controlling the layout x, y the other two controlling the translate x, y).
/* imports are missing */
public class TransReloc extends Application{
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Rectangle rect = new Rectangle(100, 50, Color.BLUE);
root.getChildren().add(rect);
VBox controlGroup = new VBox();
Slider relocX = new Slider(-100, 100, 0 );
Slider relocY = new Slider(-100, 100, 0 );
Slider transX = new Slider(-100, 100, 0 );
Slider transY = new Slider(-100, 100, 0 );
rect.layoutXProperty().bind(relocX.valueProperty());
rect.layoutYProperty().bind(relocY.valueProperty());
rect.translateXProperty().bind(transX.valueProperty());
rect.translateYProperty().bind(transY.valueProperty());
controlGroup.getChildren().addAll(relocX, relocY, transX, transY);
root.getChildren().add(controlGroup);
controlGroup.relocate(0, 300);
Scene scene = new Scene(root, 300, 400, Color.ALICEBLUE);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

layout coordinates are used by Layout Managers like StackPane or VBox to control their children location. Group (and Pane) leaves children layout to developer thus there is no difference from translate functionality.
So generally you should only change translate coordinates for fine location tuning and leave layout to layout managers (actually you can't change layoutX, layoutY for nodes inside non Group/Pane layout managers)
As an example try to run next code and resize window to see how StackPane recalculates layoutBounds
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
Rectangle rect = new Rectangle(100, 50, Color.BLUE);
root.getChildren().add(rect);
Scene scene = new Scene(root, 300, 300, Color.ALICEBLUE);
rect.layoutXProperty().addListener( (e) -> {
System.out.println(rect.getLayoutX() + ":" + rect.getLayoutY());
});
primaryStage.setScene(scene);
primaryStage.show();
}

Another difference is that when you call Node.getBoundsInLocal(), will calculate the LayoutX, LayoutY and all the applied Effects. But, Node.getBoundsInParent() will get calculated with LayoutX, LayoutY, all applied Effects plus all transformations (rotation, translation and scaling). So you can use LayoutX/Y properties as a main position and use translateX/Y as a second or an alternative way to move the node. And the other difference is discussed above, I mean not to copy from Sergey Grinev.

Related

Layouting problems with JavaFX Region

I want to write a new class that extends Region containing a StackPane inside. But I'm getting into trouble when I add insets to it like padding or a border. Here is a simplified example of the class:
public class CustomPane extends Region
{
private ToggleButton testControl = new ToggleButton("just a test control");
private StackPane rootPane = new StackPane(testControl);
public CustomPane()
{
getChildren().add(rootPane);
setStyle("-fx-border-color: #257165; -fx-border-width: 10;");
}
}
And that is how the result looks like:
If I try to move the StackPane by calling
rootPane.setLayoutX(10);
rootPane.setLayoutY(10);
then the Region just grows:
But really I wanted it to look like this:
(The third image was created by extending StackPane instead of Region, which already manages the layouting stuff correctly. Unfortunately I have to extend Region since I want to keep getChildren() protected.)
Okay, I tried to handle the layout calculation but I didn't come up with it. Could experts give me some advise?
StackPane uses the insets for layouting the (managed) children. Region doesn't do this by default. Therefore you need to override the layoutChildren with something that uses these insets, e.g.:
#Override
protected void layoutChildren() {
Insets insets = getInsets();
double top = insets.getTop(),
left = insets.getLeft(),
width = getWidth() - left - insets.getRight(),
height = getHeight() - top - insets.getBottom();
// layout all managed children (there's only rootPane in this case)
layoutInArea(rootPane,
left, top, // offset of layout area
width, height, // available size for content
0,
HPos.LEFT,
VPos.TOP);
}

JavaFX custom layout of nodes [duplicate]

This question already has answers here:
Get the height of a node in JavaFX (generate a layout pass)
(2 answers)
Closed 8 years ago.
I am developing an application for which it is necessary to layout nodes besides each other (or on top of each other etc.). However, this layout is only an initial placement and the user is able to move these nodes arbitrarily. How is this done in the correct way in JavaFX? I will explain my problem with a simplified example:
Assume I have 2 rectangles and want to place rect2 to the right of rect1.
// create first rectangle at position x= 5, y=5
rect1 = rectangle(5,5);
// create second rectangle to the right of rect1
rect2 = rectangle(5+rect1.width(), 5);
In this scenario JavaFX will not yet have determined the width of rect1 and it will be zero. Intuitively, I would perform a call that lets JavaFX draw rect1 and thus determine its width and afterwards add rect2. See the following example:
// create first rectangle at position x= 5, y=5
rect1 = rectangle(5,5);
// let JavaFX draw rect1 (width will be calculated and set)
draw();
// create second rectangle to the right of rect1
rect2 = rectangle(5+rect1.width(), 5);
Unfortunately I haven't found a method that does what I want. My current workaround makes use of Platform.runLater() but this does not work properly all the time. If my understanding of bindings is correct, bindings are also not suitable for this problem. I only want to initially layout the nodes, so I would have to remove the binding after the initial layout (or else rect2 would move if rect1 is moved).
Thanks in advance for any help.
EDIT: Here is a minimal working example. The width of the button is 0. I tried calling root.layout() to force a layout pass etc. but it does not seem to work.
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
btn.setText("Say 'Hello World'");
root.getChildren().add(btn);
// prints out 0
System.out.println(btn.getWidth());
}
}
Given the example from above, if I set the scene of the stage to null and then reset it, the button width will be set correctly when calling System.out.println(). It seems that this forces a layout pass on the whole stage? However, this just seems to be another workaround, in particular I have performance concerns.
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
btn.setText("Say 'Hello World'");
root.getChildren().add(btn);
// reset scene
primaryStage.setScene(null);
primaryStage.setScene(scene);
// prints out 107.0
System.out.println(btn.getWidth());
}

Add fixed positioned layer to FlowPane [duplicate]

This question already has answers here:
Add fixed positioned Combobox inside FlowPane
(2 answers)
Closed 9 years ago.
I have a FlowPane with panels which will be used to display data in front of the user.
![enter image description here][1]
I added also scrollpane when the number of the panels is bigger than the visible area.
I also want to add filter which will sort the panels by type and will display only the appropriate. The red area will hold the ComboBox which will be the filter.
And as you can see the red are pushes down the FlowPane which will make a gap between the top component and the scroll when I make the area transparent.
Is there a way to use the z-index and place the red are in front of the FlowPane? Or some other solution?
This is the result that I would like to get:
![enter image description here][2]
Investigate this example based on your code in previous questions:
public class Demo extends Application {
#Override
public void start(Stage stage) throws Exception {
StackPane stackPane = new StackPane();
stackPane.setAlignment(Pos.TOP_LEFT);
stackPane.getChildren().addAll(infrastructurePane(), getFilterPane());
Scene scene = new Scene(stackPane);
stage.setScene(scene);
stage.show();
}
public Pane getFilterPane() {
ObservableList<String> options =
FXCollections.observableArrayList(
"Option 1", "Option 2", "Option 3");
ComboBox<String> combo = new ComboBox<String>(options);
HBox pane = new HBox();
pane.setPadding(new Insets(20));
pane.setStyle("-fx-background-color: rgba(255,0,85,0.4)");
pane.getChildren().add(combo);
pane.setMaxHeight(40);
// Optional
//pane.setEffect(new DropShadow(15, Color.RED));
return pane;
}
public ScrollPane infrastructurePane() {
final FlowPane flow = new FlowPane();
flow.setPadding(new Insets(5, 5, 5, 5));
flow.setVgap(5);
flow.setHgap(5);
flow.setAlignment(Pos.CENTER);
final ScrollPane scroll = new ScrollPane();
scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // Horizontal scroll bar
scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // Vertical scroll bar
scroll.setFitToHeight(true);
scroll.setFitToWidth(true);
scroll.setContent(flow);
// scroll.viewportBoundsProperty().addListener(new ChangeListener<Bounds>() {
// #Override
// public void changed(ObservableValue<? extends Bounds> ov, Bounds oldBounds, Bounds bounds) {
// flow.setPrefWidth(bounds.getWidth());
// flow.setPrefHeight(bounds.getHeight());
// }
// });
//flow.setPrefWrapLength(170); // preferred width allows for two columns
flow.setStyle("-fx-background-color: yellow;");
for (int i = 0; i < 28; i++) {
flow.getChildren().add(generateRectangle());
}
String cssURL = "/com/dx57dc/css/ButtonsDemo.css";
String css = this.getClass().getResource(cssURL).toExternalForm();
flow.getStylesheets().add(css);
return scroll;
}
public Rectangle generateRectangle() {
final Rectangle rect2 = new Rectangle(10, 10, 10, 10);
rect2.setId("app");
rect2.setArcHeight(8);
rect2.setArcWidth(8);
//rect2.setX(10);
//rect2.setY(160);
rect2.setStrokeWidth(1);
rect2.setStroke(Color.WHITE);
rect2.setWidth(220);
rect2.setHeight(180);
rect2.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
rect2.setFill(Color.ALICEBLUE);
}
});
return rect2;
}
public static void main(String[] args) {
launch(args);
}
}
EDIT:
As per comment, here is the combo without pane. Since there is no pane the mouse events will not be blocked. Replace only this method with above one:
public ComboBox getFilterPane() {
ObservableList<String> options =
FXCollections.observableArrayList(
"Option 1", "Option 2", "Option 3");
ComboBox<String> combo = new ComboBox<String>(options);
combo.setTranslateX(10);
combo.setTranslateY(10);
return combo;
}
if you're using JavaFX 8, you can try a Notification Pane from ControlsFX project
It looks like:
It's pretty unclear to get which behaviour you don't want and which one you want.
This sentence "And as you can see the red are pushes down the FlowPane which will make a gap between the top component and the scroll when I make the area transparent." is particularly hard to understand.
But if you just want to "use the z-index and place the red are in front of the FlowPane?", maybe all you're asking for is just a StackPane ?
StackPane lays out its children in a back-to-front stack.
The z-order of the children is defined by the order of the children
list with the 0th child being the bottom and last child on top. If a
border and/or padding have been set, the children will be layed out
within those insets.
http://docs.oracle.com/javafx/2/api/javafx/scene/layout/StackPane.html
If you want the red area be part of the ScrollPane:
Create a VBox
Add The Red Area Component to VBox
Add the FlowPane to VBox
Set VBox as the ScrollPanes Content
If the Layout with VBox's doenst look statisfying try Borderpane and set the "Red Area" top and your flowpane as center.
Is there a way to use the z-index and place the red are in front of the FlowPane? Or some other solution?
see QuidNovi's answer

A simple JavaFX 2.x animation task

I have done animations in FlashProfessional (CS 6), which sucks by the way (crashes constantly without saving last modifications, produces enormous files, works inconsistently and so on). I have hard time to figure out how the following simple task can be done in JavaFX 2.x (probably because my background is in Flash): a rectangle that exists in a constant location from t=0 to t=100, and after that it is deleted from the Scene.
In Flash, I could create a keyframe at t=0 in which I draw a rectangle. Then I create second keyframe at t=100 in which the rectangle is deleted. That simple.
In JavaFX, why I can’t just write timeline.getKeyFrames().addAll(new KeyFrame(new Duration(100), new Rectangle(10, 10, 25, 25))); or like.
Please help me and provide the code. I’m lost in these KeyValues and Java properties, why I need those anyway…
To achieve that task you can just remove rectangle after 100 ms. JavaFX unlike Flash is not built about keyframes -- they are optional functionality and used only if you need real animation, e.g. scaling of an object. See next tutorial for more info: http://docs.oracle.com/javafx/2/animations/jfxpub-animations.htm
And demonstrating code:
public void start(Stage primaryStage) {
final Rectangle rect1 = new Rectangle(10, 70, 50, 50);
final Rectangle rect2 = new Rectangle(10, 150, 50, 50);
Button btn = new Button("Play");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
// this "timeline" just call a handler after 500 ms which hides rectangle
TimelineBuilder.create().keyFrames(new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
rect1.setVisible(false);
}
})).build().play();
// this timeline hides rectangle 2 with animation
// changing scaleXProperty() from 1 (default) to 0
TimelineBuilder.create().keyFrames(
new KeyFrame(
Duration.millis(500),
new KeyValue(rect2.scaleXProperty(), 0))
).build().play();
}
});
Pane root = new Pane();
root.getChildren().addAll(rect1, rect2, btn);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}

JavaFX 2 -fx-effect breaks opacity

Has anyone else found that adding -fx-effect in a style prevents opacity working?
Here is a simple example
public class TestGUI extends Application {
#Override
public void start(final Stage primaryStage) {
Line line = LineBuilder.create()
.startX(150)
.startY(0)
.endX(150)
.endY(250)
.build();
Button btn = ButtonBuilder.create()
.text("Open countdown!")
// this breaks the opacity!
.style("-fx-effect: dropshadow(three-pass-box, grey, 5, 0.5, 2, 5);")
.opacity(0.6)
.build();
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Button clicked");
}
});
StackPane root = new StackPane();
root.getChildren().addAll(line, btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Test Application");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Take out the style clause and you can see the line through the button.
Is this a bug or am I missing something.
The shadow is actually a shadow of the translucent node and translucent itself but because you are layering a translucent node on top of a tranlucent shadow, the overall result is still translucent, but much more opaque than if no shadow had been applied to the node. Similar to layering two 50 percent opaque nodes. The intersected area of the two layered nodes will be 75 percent opaque.
In your sample, you set the opacity to 0.6, so the combined opacity of the node + shadow is 0.6 + 0.4 * 0.6 = 0.84. Plus the shadow is a darker color than the effected node to begin with. This makes it difficult to see the line behind the effected node - but you can still just see it because the node + it's effect is not fully opaque. To show what is going on more clearly, I set the opacity of your sample to 0.2, making the combined opacity 0.36. You can see the result in the screenshot below where the line behind the effected node is still clearly visible.
Generally, shadows and opaque nodes visually don't mix and look all that good together

Resources