ペインのボタンに同じ幅を設定したいのですが、ステージを表示する前にボタンの幅がありません。ステージを表示せずに幅を取得するにはどうすればよいですか?
幅が定義されていないために機能しないコードの例:
public static HBox createHorizontalButtonBox(final List<Button> buttons, final Pos alignment, final double spacing, final boolean sameWidth) {
HBox box = new HBox(spacing);
box.setAlignment(alignment);
box.getChildren().addAll(buttons);
if (sameWidth && buttons.size() > 1) {
double max = maxWidth(buttons);
for (Button b : buttons) {
b.setPrefWidth(max);
}
}
return box;
}
レイアウトペインにレイアウトを任せます。
使用しているレイアウトペインが希望どおりのレイアウトを提供していない場合は、次のいずれかを実行します。
メソッドには、すべての子ノードのサイズを同じサイズにするかどうかを示すパラメーターがあります。すべての子ノードのサイズを同じサイズにするペインはTilePaneであるため、要素をレイアウトするためにそれを選択できます。A GridPaneはそれがサイズの要素と同じサイズに設定可能な制約があるためにも動作します。ストックHBoxは、すべての子要素のサイズを同じサイズにするプロパティがないため、直接機能しません。必要に応じて、HBoxをサブクラス化してこれを行うことができます(layoutChildren()をオーバーライドすることにより)。
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SameSizeButtons extends Application {
@Override
public void start(Stage stage) {
VBox layout = new VBox(
10,
createHorizontalButtonBox(
Arrays.stream("All buttons the same width".split(" "))
.map(Button::new)
.collect(Collectors.toList()),
Pos.CENTER,
10,
true
),
createHorizontalButtonBox(
Arrays.stream("All buttons different widths".split(" "))
.map(Button::new)
.collect(Collectors.toList()),
Pos.CENTER_RIGHT,
10,
false
)
);
layout.setPadding(new Insets(10));
layout.getChildren().forEach(node ->
node.setStyle("-fx-border-color: red; -fx-border-width: 1px;")
);
stage.setScene(new Scene(layout));
stage.show();
}
public static Pane createHorizontalButtonBox(
final List<Button> buttons,
final Pos alignment,
final double spacing,
final boolean sameWidth) {
return sameWidth
? createSameWidthHorizontalButtonBox(
buttons,
alignment,
spacing
)
: createDifferentWidthHorizontalButtonBox(
buttons,
alignment,
spacing
);
}
private static Pane createSameWidthHorizontalButtonBox(
List<Button> buttons,
Pos alignment,
double spacing)
{
TilePane tiles = new TilePane(
Orientation.HORIZONTAL,
spacing,
0,
buttons.toArray(
new Button[buttons.size()]
)
);
tiles.setMinWidth(TilePane.USE_PREF_SIZE);
tiles.setPrefRows(1);
tiles.setAlignment(alignment);
buttons.forEach(b -> {
b.setMinWidth(Button.USE_PREF_SIZE);
b.setMaxWidth(Double.MAX_VALUE);
});
return tiles;
}
private static Pane createDifferentWidthHorizontalButtonBox(
List<Button> buttons,
Pos alignment,
double spacing)
{
HBox hBox = new HBox(
spacing,
buttons.toArray(
new Button[buttons.size()]
)
);
hBox.setAlignment(alignment);
buttons.forEach(b ->
b.setMinWidth(Button.USE_PREF_SIZE)
);
return hBox;
}
public static void main(String[] args) {
launch(args);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加