I am working on a personal graph editor project, and I want to create flowchart-like graph for automatic code generation. My first idea was Canvas
and GraphicsContext
, but it turns out to be too complicated as I have to draw everything manually. So I have switched to Shape
.
Basically, every node is a Shape
with other standard ui components over it, such as Label
, ChoiceBox
etc. Since every node represents a program function, and I want to use these ui components to choose the function's input.
I am doing some experiments with StackPane
, a Rectangle
in the background with some Label
s over it:
public class RectangleNode extends StackPane {
private double x;
private double y;
private VBox vbox;
private Rectangle rect;
public RectangleNode(double x, double y) {
super();
setAlignment(Pos.CENTER);
this.x = x;
this.y = y;
Label label1 = new Label("Hello world");
Label label2 = new Label("Hello JavaFX");
vbox = new VBox(label1, label2);
rect = new Rectangle();
rect.setStroke(Color.ALICEBLUE);
rect.setStrokeWidth(2);
rect.setX(this.x);
rect.setY(this.y);
getChildren().addAll(rect, vbox);
}
public void updateSize () {
double width = vbox.getLayoutBounds().getWidth();
double height = vbox.getLayoutBounds().getHeight();
System.out.println("width vbox: " + width + "px");
System.out.println("height vbox: " + height + "px");
rect.setWidth(width + 10);
rect.setHeight(height + 10);
}
}
The node is placed inside a Pane
as it offers absolute positioning of components:
public class StackPaneTest extends Application {
public void start(Stage stage) throws Exception {
Pane root = new Pane();
stage.setTitle("StackPane Test");
stage.setScene(new Scene(root, 480, 360));
stage.show();
RectangleNode pane = new RectangleNode(100, 100);
root.getChildren().add(pane);
pane.updateSize();
}
public static void main(String[] args) {
launch(args);
}
}
Then I have discovered a few problems here:
- the
getLayoutBounds().getWidth()
andgetLayoutBounds().getHeight()
always return zero, so I cannot resize the rectangle according the size of labels, how can I get the real size ofvbox
? - The
StackPane
is always in the top-left corer ofPane
even I have set the coordinates ofRectangle
withsetX
andsetY
, how can I position it absolutely? - Is
StackPane
the right approach?
Thanks.