0

I have a problem with my button size in JavaFX. I want to have fixed size buttons but when I change text on the buttons, changes button size aswell.

I have 5 buttons and 5 random numbers between 1 - 20. Buttons with single digit is smaller then buttons with two digits. I want both same size.

What can I do?

asked Nov 25, 2014 at 18:25
2
  • 1
    You can implement a container that contains all the buttons, say ButtonPane, and layouts all of them to the maximum preferred width among all the buttons. That is, ButtonPane overrides the layoutChildren() method. Commented Nov 25, 2014 at 19:15
  • 1
    As a special case, if you put your buttons into a VBox with fillWidth=true (the default), they will all be resized to the width of the VBox, i.e. to the same width. Commented Nov 25, 2014 at 19:25

1 Answer 1

2

Here is one way to do this. The buttons go in a TilePane, the TilePane goes in a group so that everything in it remains at it's preferred size. A preferred size is set on each button.

fixed width buttons

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
import java.util.Random;
public class FixedSizes extends Application {
 private static final int NUM_BUTTONS = 5;
 private static final int MAX_BUTTON_VALUE = 20;
 private static final Random random = new Random(42);
 @Override
 public void start(Stage stage) throws Exception {
 stage.setScene(new Scene(generateButtonLayout()));
 stage.show();
 }
 private Parent generateButtonLayout() {
 TilePane layout = new TilePane();
 layout.setHgap(10);
 layout.setPrefColumns(NUM_BUTTONS);
 layout.getChildren().setAll(createButtons());
 layout.setPadding(new Insets(10));
 return new Group(layout);
 }
 private Button[] createButtons() {
 Button[] buttons = new Button[NUM_BUTTONS];
 for (int i = 0; i < buttons.length; i++) {
 buttons[i] = createButton();
 }
 return buttons;
 }
 private Button createButton() {
 Button button = new Button(generateButtonText());
 button.setOnAction(event -> button.setText(generateButtonText()));
 button.setPrefWidth(50);
 return button;
 }
 private String generateButtonText() {
 return "" + (random.nextInt(MAX_BUTTON_VALUE) + 1);
 }
 public static void main(String[] args) {
 launch(args);
 }
}
answered Nov 26, 2014 at 0:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.