Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create resizing spacers in JavaFX?

Tags:

layout

javafx

First of all, I'm a long time Java/Swing developer. I recently installed JavaFX 2.2 to play around with.

I'm creating a fairly simple app, whose main window has a toolbar on top and content in the rest of the window. The obvious way to accomplish this is to use a BorderPane, and stick a ToolBar into the top section. So far, so good. However, I would like some of the controls in the toolbar to be at the left edge of the window, and some at the right edge. I can find no way to do this. I can put an invisible spacer object into the toolbar, but I only know how to give it a fixed width; it doesn't resize when the window is resized.

So I thought that instead of using a ToolBar object, I'll just use an HBox; it should be equivalent to a horizontally-oriented Swing Box object, right? And the Swing Box class has a createHorizontalGlue() method that inserts an auto-sizing spacer. Well, I can't find an equivalent in the JavaFX HBox class. Is there no simple way to do this?

like image 760
Karl von L Avatar asked Aug 25 '12 02:08

Karl von L


2 Answers

I figured out how to do it using an HBox instead of a ToolBar to hold the controls; the key is the HBox.setHgrow() method, which allows you to set a spacer object to grow to fill the available space. I still don't know if it's possible to do this with an actual ToolBar instance.

/**
 * Creates and populates the Node that serves as the window toolbar.
 *
 * @return a newly constructed and populated toolbar component
 */
private Node makeToolbar() {
    // Auto-sizing spacer
    Region spacer = new Region();
    HBox.setHgrow(spacer, Priority.ALWAYS);

    // Horizontal box containing toolbar controls
    HBox box = new HBox();
    box.setPadding(new Insets(8));
    box.setAlignment(Pos.CENTER);
    box.getChildren().addAll(openButton, spacer, resizeSlider);

    // Colored background panel with drop shadow
    Pane bgRect = new Pane();
    bgRect.setStyle("-fx-background-color: #e0e0e0;");
    bgRect.setEffect(DropShadowBuilder.create().width(1).build());

    // StackPane to hold box and rectangle
    StackPane stack = new StackPane();
    stack.getChildren().addAll(bgRect, box);

    return stack;
}
like image 58
Karl von L Avatar answered Oct 18 '22 19:10

Karl von L


i do it this way:

private Node makeFooter(Node left, Node right) {
        ToolBar footer = new ToolBar();
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);     
        spacer.setMinWidth(Region.USE_PREF_SIZE);
        footer.getItems().addAll(left, spacer, right);
        return footer;
}

hope i could help someone

like image 41
Rami.Q Avatar answered Oct 18 '22 19:10

Rami.Q