How can I create resizing spacers in 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?

8/25/2012 2:30:25 AM

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.getChildren().addAll(openButton, spacer, resizeSlider);

    // Colored background panel with drop shadow
    Pane bgRect = new Pane();
    bgRect.setStyle("-fx-background-color: #e0e0e0;");

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

    return stack;
8/25/2012 4:11:26 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow