GridBagLayout 锚点和 JScrollPane 问题

GridBagLayout anchor & JScrollPane issues

我有以下class

public class Demo {

private JFrame mainFrame;

static public Color BGCOLOUR1 = new Color(240, 240, 240);

public Demo() {
    mainFrame = new JFrame("Demo");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setLayout(new BorderLayout());
    mainFrame.setSize(900, 800);

    JPanel centralPanel = new JPanel();
    centralPanel.setOpaque(true);
    centralPanel.setBackground(BGCOLOUR1);
    centralPanel.setLayout(new GridBagLayout());
    centralPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20),
            BorderFactory.createTitledBorder("Panel")));

    JPanel insidePanel = new JPanel();
    insidePanel.setOpaque(true);
    insidePanel.setBackground(BGCOLOUR1);
    insidePanel.setLayout(new BorderLayout());
    insidePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Inside panel"),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));


    JTextArea insidePanelText = new JTextArea(6, 50);
    insidePanelText.setLineWrap(true);

    insidePanel.add(insidePanelText);

    centralPanel.add(insidePanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0));

    JScrollPane scrollPane = new JScrollPane(centralPanel);
    mainFrame.add(scrollPane);
}

当我将 GridBagConstraints 锚点设置为 NORTH 时,为什么内部面板位于 centralPanel 的中心(垂直)?我希望它位于顶部。

此外,如果我按照示例将 centralPanel 添加到 JScrollPane 中,然后再将其添加到 mainFrame 中,我可以将应用程序的大小调整得更大一些,但一旦我将它的大小调整得更小(即使它仍然比我最初启动它时要大)出现一个滚动条。我怎样才能防止这种情况发生?

编辑:为了说明滚动问题(我在拍摄这些屏幕时 pack 编辑了框架):

当我启动应用程序时它没有滚动条

我将 window 调整得更大,然后又变小了。只要我把它变小,就会出现滚动条。

GridBagLayout 而言,根据您提供的属性,它被布置到单元格的 NORTH

GridBagLayout 主要根据组件的首选大小工作,并计算每个组件围绕父容器中心的位置。

如果,而不是:

new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH,
        GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)

我使用类似的东西:

new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH,
        GridBagConstraints.HORIZONTAL, new Insets(10, 10, 10, 10), 0, 0)

它将产生所需的结果。

基本上,通过使用 gridy 并将其设置为 1,我们要求 GridBagLayout 将所有剩余的垂直 space 分配给此单元格,但是因为我们没有填充单元格,内容被推送到单元格

NORTH

Also, if I add the centralPanel in a JScrollPane before adding it to the mainFrame as per the example I can resize the application larger just fine, but as soon as I resize it smaller (even though it is still larger than I originally started it) a scroll bar appears. How can I prevent that from happening?

我无法真正复制这个特定问题,我可以使用 packsetSize 并将 window 的大小调整为更小的 "packed" 大小和滚动滚动条会出现,但是一旦我将 window 的大小调整到 "packed" 之外,滚动条就会消失