gpt4 book ai didi

java - 在 JavaFX 2 中将工具栏按钮设置为方形且大小相同

转载 作者:行者123 更新时间:2023-11-30 04:27:48 25 4
gpt4 key购买 nike

在下面的代码中,我有一个工具栏,并向其中添加了各种大小的按钮。我希望按钮是方形的并且大小相同。因此,基本上找到所有按钮中最长的宽度或高度,并将所有其他按钮的宽度和高度设置为该尺寸。然而,按钮可以改变大小,所以我认为我需要一个绑定(bind)。我不太明白 - 有人知道该怎么做吗?

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

public class ToolBarButtonTest extends Application {
@Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
Scene scene = new Scene(borderPane, 500, 500);

ToolBar toolBar = new ToolBar();

Button button1 = new Button("s");
Button button2 = new Button("ss");
Button button3 = new Button("sss");

toolBar.getItems().addAll(button1, button2, button3);

borderPane.setTop(toolBar);

stage.setScene(scene);
stage.show();
}

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

谢谢,尼克。

最佳答案

给你。此示例将使用 CSS 将按钮形状变成正方形,并安装验证监听器来跟踪按钮的布局更改并相应地更新宽度。

public class SquareButtons extends Application {
@Override
public void start(final Stage stage) throws Exception {
/* Assume these are your toolbar elements */
final Button[] buttons = new Button[]{
new Button("Short"),
new Button("Slightly longer"),
new Button("Very very very long button")
};

/* This would, of course, belong in a style sheet - it turns the buttons square */
for (Button b : buttons)
b.setStyle("-fx-background-radius: 0");

/* This will set the pref width/height of all your buttons to the maximum of the pref width/height of the larget one */
final InvalidationListener listener = new InvalidationListener() {
public void invalidated(final Observable observable) {
double size = 0;
for (Button b : buttons) {
size = Math.max(size, b.prefWidth(Integer.MAX_VALUE));
size = Math.max(size, b.prefHeight(Integer.MAX_VALUE));
}

for (Button b : buttons) {
b.setPrefWidth(size);
b.setPrefHeight(size);
}
}
};

for (Button b : buttons)
b.widthProperty().addListener(listener);

final ToolBar toolbar = new ToolBar();
toolbar.getItems().addAll(buttons);

final Scene scene = new Scene(toolbar);
stage.setScene(scene);
stage.setWidth(800);
stage.setHeight(200);
stage.show();
}

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

更新:没有足够彻底地阅读问题,请参阅评论。

关于java - 在 JavaFX 2 中将工具栏按钮设置为方形且大小相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com