【发布时间】:2015-08-30 05:05:37
【问题描述】:
我正在尝试在 javafx 中创建自定义工具栏。该工具栏应该能够在其表面的中心、左侧和右侧(三个部分)显示控件。 问题是我不知道要做到这一点。我阅读了许多与此问题相关的提示,但它们对我不起作用或者我做错了什么......
无论如何,我写了几个方法,它们代表了实现我的工具栏的不同方法,但它们都不能正常工作。 这里有我的尝试:
-
使用 HBox Hgrow 属性作为弹簧。没用。
public ToolBar createToolBar() { ToolBar toolBar = new ToolBar(); Pane emptyPane = new Pane(); HBox spring = new HBox(emptyPane); spring.setHgrow(emptyPane, Priority.ALWAYS); toolBar.getItems().addAll(spring, new Label("LABEL")); return toolBar; }
2.左右两边都可以,中间的怎么定义呢?
public AnchorPane createToolBar2()
{
AnchorPane toolBar = new AnchorPane();
Label leftLabel = new Label("left");
Label rightLabel = new Label("right");
toolBar.getChildren().addAll(leftLabel, rightLabel);
toolBar.setLeftAnchor(leftLabel, 0.0);
toolBar.setRightAnchor(rightLabel, 0.0);
return toolBar;
}
-
这种方法适用于布局,但我无法监听来自左侧和中心部分的事件,因为它们被右侧部分覆盖(原因是 StackPane),所以这个解决方案也没用。
public StackPane createToolBar3() { StackPane toolBar = new StackPane(); Button left = new Button("left button"); Button right = new Button("right button"); Button center = new Button("center button"); HBox leftSection = new HBox(left); leftSection.setAlignment(Pos.CENTER_LEFT); HBox centerSection = new HBox(center); centerSection.setAlignment(Pos.CENTER); HBox rightSection = new HBox(right); rightSection.setAlignment(Pos.CENTER_RIGHT); toolBar.getChildren().addAll(leftSection, centerSection, rightSection); left.setOnAction(event -> System.out.println("left")); right.setOnAction(event -> System.out.println("right")); center.setOnAction(event -> System.out.println("center")); return toolBar; }
我在该代码块中调用的上述方法:
@Override
public void start(Stage stage) {
BorderPane borderPane = new BorderPane();
borderPane.setPrefWidth(500);
borderPane.setPrefHeight(300);
borderPane.setTop(createToolBar4());
stage.setScene(new Scene(borderPane));
stage.show();
}
我将不胜感激。
【问题讨论】:
-
看看this post。您可以将帖子中的 ImageView、Image 和 VBox 替换为您各自的控件。
标签: java javafx alignment toolbar