在JavaFX中向窗口动态添加元素
我想要一个显示图像的窗口。这是窗口的主要用途。但是,也可以在顶部设置控件。这个数字事先不知道。可能是3或15。它们现在应该堆在那里。所以上面的部分变大了,下面的图像被向下推在JavaFX中向窗口动态添加元素,java,user-interface,javafx,Java,User Interface,Javafx,我想要一个显示图像的窗口。这是窗口的主要用途。但是,也可以在顶部设置控件。这个数字事先不知道。可能是3或15。它们现在应该堆在那里。所以上面的部分变大了,下面的图像被向下推 void createNewWindow() { Stage stage = new Stage(); BorderPane pane = new BorderPane(); ImageView imageView = new ImageView("path"); pane.setCenter
void createNewWindow() {
Stage stage = new Stage();
BorderPane pane = new BorderPane();
ImageView imageView = new ImageView("path");
pane.setCenter(imageView);
HBox controlBox = new HBox(10);
pane.setTop(controlBox);
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.setResizable(true);
stage.show();
}
这个代码几乎不起作用。我必须手动添加宽度和高度,因为场景或舞台找不到适合的东西。当我稍后在顶部的HBox中添加按钮时,窗口的大小不会增加,HBox的高度也不会保持在0。只有图像被按下,它不再完全可见
我该怎么做呢?您应该在controlBox的每个子级上使用该方法
这将使按钮彼此相邻对齐,减小大小,以便所有按钮都可以放在一行中,并填充可用空间。JavaFX节点可动态重新调整大小,即子节点将填充父节点提供的空间,父节点将根据子节点需要的最小空间进行扩展 我不会面对您在尝试将HBox添加到边框窗格时提出的问题。添加HBox后,边框窗格高度增加的幅度大于图像高度。如果要查看图像是否被按下,请尝试将VBox替换为HBox 这是一个简单的例子,我使用365的图像和26的HBox,这导致边框窗格的高度为391 控制台上的输出
为了让窗口随着窗口内内容的扩展而增长,我确实这样做了,但还没有找到其他解决方案 在这种情况下,将从MainController打开一个新窗口,该窗口的内容可以增长,我希望该新窗口也随之增长,因此在新窗口的控制器中,我添加了一个侦听器
containerPane.heightProperty().addListener((observable, oldValue, newValue) -> {
MainController.theStage.setHeight(MainController.theStage.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
});
在你的情况下,它是有效的。但是如果我在后台显示之后添加按钮,它就不会再调整大小了。如果以后添加元素,你会不得不重新构建UI吗?
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class BorderPaneHeight extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane borderPane = new BorderPane();
HBox box = new HBox(10);
ImageView imageView = new ImageView(new Image("file:///home/itachi/Pictures/aaa.png")); // Replace with your image path
Button button1 = new Button("Add");
Button button2 = new Button("Add");
box.getChildren().addAll(button1, button2);
borderPane.setTop(box);
borderPane.setCenter(imageView);
Scene scene = new Scene(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
System.out.println("Image height : " + imageView.getImage().getHeight());
System.out.println("Hbox height : " + box.getHeight());
System.out.println("BorderPane Height : " + borderPane.getHeight());
}
public static void main(String[] args) {
launch(args);
}
}
Image height : 365.0
Hbox height : 26.0
BorderPane Height : 391.0
containerPane.heightProperty().addListener((observable, oldValue, newValue) -> {
MainController.theStage.setHeight(MainController.theStage.getHeight() + (newValue.doubleValue() - oldValue.doubleValue()));
});