2

除非另有说明,否则以下组件都没有最小、最大或首选高度:我有一个带 BorderLayout 的 JPanel。在 BorderLayout 的中心有一个 JPanel。在 PAGE_START 处有一个 JFXPanel。JFXPanel 已设置一个包含一个 BorderPane 的场景,该 BorderPane 又包含另一个 BorderPane(具有由 FXML 定义的最小、最大和首选高度)和一个 FlowPane。

但是,将元素添加到 FlowPane 时,JFXPanel 不会调整大小。FlowPane 的高度保持为其顶部和底部填充的总和 - 大概是因为这是在 JFXPanel 中首次设置场景时的正确高度。

因此,FlowPane 的元素被切断(或在包装后完全隐藏)。(如果我手动将 JFXPanel 设置得更大,我可以看到 FlowPane 正在正确调整大小,所以这不是问题。)

为什么我的 JFXPanel 没有调整大小?JFXPanel 是不是根本不适合根据场景调整大小,还是需要一些其他方法调用(例如 invalidate())?或者问题的根源是 LayoutManager 之一?

MCVE

以下代码生成如下所示的框架:

在此处输入图像描述

然而,如果我在设置 JFXPanel 的场景之前将元素添加到 FlowPane ,它看起来像这样(这是可取的):

在此处输入图像描述

显然,在实际代码中,随着我们的进行,新元素会被添加到 FlowPane 中或从中删除,因此不能等到设置场景之后。希望 JFXPanel 像 FlowPane 一样动态调整大小。

public static void main(String[] args)
{
    JFXPanel topPanel = new JFXPanel();

    JPanel centerPanel = new JPanel();
    centerPanel.setBorder(BorderFactory.createLineBorder(Color.GREEN));

    JPanel mainPanel = new JPanel(new BorderLayout());
    mainPanel.add(topPanel, BorderLayout.PAGE_START);
    mainPanel.add(centerPanel, BorderLayout.CENTER);

    JFrame frame = new JFrame("Main Frame");
    frame.setContentPane(mainPanel);
    frame.setUndecorated(true);
    frame.setSize(new Dimension(300, 300));

    BorderPane root = new BorderPane();
    BorderPane borderPane = new BorderPane();
    borderPane.setMinHeight(100);
    borderPane.setMaxHeight(100);
    borderPane.setStyle("-fx-border-color: red;");

    FlowPane flowPane = new FlowPane();
    flowPane.setStyle("-fx-border-color: blue;");

    root.setCenter(borderPane);
    root.setBottom(flowPane);

    Platform.runLater(() -> topPanel.setScene(new Scene(root)));

    SwingUtilities.invokeLater(() -> frame.setVisible(true));

    // Now add some elements to the FlowPane
    Platform.runLater(() ->
    {
        for (int i = 0; i < 5; i++)
        {
            flowPane.getChildren().add(new PinkSquare());
        }
    });
}

private static class PinkSquare extends HBox
{
    private PinkSquare()
    {
        super();
        setMinHeight(50);
        setMinWidth(50);
        setStyle("-fx-background-color: pink;");
    }
}
4

0 回答 0