Javafx 等距切换按钮

Javafx equally spanned toggle button

我需要制作一组如下所示的切换按钮,白色背景为选中按钮,两个按钮占据父容器的 50% 宽度。 HBox 中放置了两个切换按钮。样式

到目前为止我试过了,卡在这个地方。

.viewType .toggle-button {
    -fx-padding: 0 2 0 2;
    -fx-background-color: #000;
    -fx-text-fill: white;
}

.viewType .toggle-button:selected {
    -fx-padding: 0;
    -fx-background-color: white;
    -fx-text-fill: black;
    -fx-border-wdith: 2;
    -fx-border-color: black;
    -fx-border-radius: 4;
}

您可以在 java 侧将按钮的 maxWidth 设置为 max double。这将使您的按钮在 HBox 中具有相同的宽度。希望有用:

btn1.setMaxWidth(Double.MAX_VALUE);
btn2.setMaxWidth(Double.MAX_VALUE);

您可以查看以下 link 以获取与调整节点大小和对齐节点相关的有用信息:

Sizing and Aligning Nodes

如果您希望两个按钮的宽度相等,请使用 GridPane 而不是 HBox,并使用列约束使两列的宽度相等:

GridPane grid = new GridPane();
grid.getColumnConstraints().addAll(createCol(), createCol());
ToggleButton toggle1 = new ToggleButton("...");
toggle1.setMaxWidth(Double.MAX_VALUE);
ToggleButton toggle2 = new ToggleButton("...");
toggle2.setMaxWidth(Double.MAX_VALUE);
grid.addRow(0, toggle1, toggle2);

// ...

private ColumnConstraints createCol() {

    ColumnConstraints col = new ColumnConstraints();
    col.setPercentWidth(50);
    col.setFillWidth(true);
    return col ;

}

您可以通过配置父级进一步控制网格窗格在其父级中的大小(详细信息取决于父级使用的窗格类型)。

SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class EqualSizedButtons extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane grid = new GridPane();
        grid.getStyleClass().add("viewType");
        grid.getColumnConstraints().addAll(createCol(), createCol());
        ToggleButton toggle1 = new ToggleButton("A");
        toggle1.setMaxWidth(Double.MAX_VALUE);
        ToggleButton toggle2 = new ToggleButton("This is really big button B");
        toggle2.setMaxWidth(Double.MAX_VALUE);
        grid.addRow(0, toggle1, toggle2);

        new ToggleGroup().getToggles().addAll(toggle1, toggle2);

        BorderPane root = new BorderPane();
        root.setBottom(grid);

        Scene scene = new Scene(root, 600, 600);
        scene.getStylesheets().add("style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    private ColumnConstraints createCol() {

        ColumnConstraints col = new ColumnConstraints();
        col.setPercentWidth(50);
        col.setFillWidth(true);
        return col ;

    }

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