'Get the height of a node in JavaFX (generate a layout pass)
How to get the height or prefer height of a node in JavaFX, I have 3 VBox and I want to add nodes to the the most freer panel, example:
Childrens Total Height of the children's(Sum)
VBoxA 5 890
VBoxB 4 610
VBoxC 2 720
in this case, the most freer is the VBoxB, I calculate the most freer pane with this method:
private int getFreerColumnIndex() {
if(columns.isEmpty())
return -1;
int columnIndex = 0;
int minHeight = 0;
for(int i = 0; i < columns.size(); i++) {
int height = 0;
for(Node n : columns.get(i).getChildren()) {
height += n.getBoundsInLocal().getHeight();
}
if(i == 0) {
minHeight = height;
} else if(height < minHeight) {
minHeight = height;
columnIndex = i;
}
if(height == 0)
break;
}
return columnIndex;
}
This method only works if I add 1 element at the time. But if I add more elements at the time:
for (int i = 0; i < 10; i++) {
SomeNode r1 = new SomeNode ();
myPane.addElement(r1);
}
the method getFreerColumnIndex return the same index. This is because the new nodes dont have heigth in local yet.
So this line:
height += n.getBoundsInLocal().getHeight();
will return 0 with the new nodes.
Anyone knows how to get the heigth of a node ?
Extra:
SomeNode extends of Node
Method addElement() at myPane:
public void addElement(final Node element) {
index = getFreerColumnIndex();
columns.get(index).getChildren().add(element);
}
Extra 2:
suppose we have 3 vbox: Before:
A B C
| | |
| |
|
Run:
for (int i = 0; i < 10; i++) {
SomeNode r1 = new SomeNode ();
myPane.addElement(r1);
}
After:
A B C
| | |
| | |
| |
|
|
|
|
|
|
|
|
Correct:
A B C
| | |
| | |
| | |
| | |
| | |
|
| = Some node
Solution 1:[1]
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.io.Closeable;
public class Sizing extends Application {
@Override
public void start(Stage stage) {
var label = new Label();
var labelHeight = label.getHeight();
System.out.println(labelHeight);
try (var s = new SizingSandbox(label)) {
labelHeight = label.getHeight();
}
System.out.println(labelHeight);
}
public static void main(String[] args) { launch(args); }
}
class SizingSandbox extends Group implements Closeable {
public SizingSandbox(Node... nodes) {
new Scene(this);
getChildren().addAll(nodes);
layItOut();
}
@Override
public void close() {
try {
getChildren().removeAll();
} catch (Exception e) { }
}
private void layItOut() {
applyCss();
layout();
}
}
// output:
// 0.0
// 17.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
