1

How do I make a vertical ButtonBar in JavaFX 8?

I want exactly the same concepts of the ButtonBar component, but ButtonBar is horizontal, I want vertical. All the buttons must be same size.

If I use a VBox I have to set the width of the buttons and of the VBox manually.

Is there a simpler way to do that without having to set widths?

ceklock
  • 6,143
  • 10
  • 56
  • 78

2 Answers2

4

You need two things: to set fillWidth to true on the VBox, and to set maxWidth on each button. The most convenient approach is probably a simple subclass of VBox:

import javafx.scene.control.Button;
import javafx.scene.layout.VBox;

public class VerticalButtonBar extends VBox {

    public VerticalButtonBar() {
        setFillWidth(true);
    }

    public void addButton(Button button) {
        button.setMaxWidth(Double.MAX_VALUE);
        getChildren().add(button);
    }

}

and then you can do things like

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class VerticalButtonBarExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        VerticalButtonBar bar = new VerticalButtonBar();
        bar.addButton(new Button("A"));
        bar.addButton(new Button("Button"));

        BorderPane root = new BorderPane();
        root.setLeft(bar);
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();
    }



    public static void main(String[] args) {
        launch(args);
    }
}

which looks like

enter image description here

See Adding a custom component to SceneBuilder 2.0 if you want to make the VerticalButtonBar visible to SceneBuilder.

Community
  • 1
  • 1
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Hm... nice answer, I wish ButtonBar could handle this, it was my expectation when I was doing some tests at SceneBuilder. – ceklock Nov 26 '15 at 15:37
  • Thinking about it though, it wouldn't work with SceneBuilder, as the FXML would effectively call `getChildren().add(button)`, not `addButton`... – James_D Nov 26 '15 at 15:39
  • I was looking for a way to make it without code, just using Scene Builder. I don't like the way I do it because have to deal with widths. At the end your way must be a good approach. – ceklock Nov 27 '15 at 04:03
1

As far as I can see, ButtonBar has no way to change this, so there is nothing SceneBuilder can do about it.

You might want to file a feature request for ButtonBar: http://bugs.java.com/

Puce
  • 37,247
  • 13
  • 80
  • 152