代码之家  ›  专栏  ›  技术社区  ›  MineRickStar

JScrollBar布局管理器和SpringLayout管理器不在一起工作

  •  1
  • MineRickStar  · 技术社区  · 2 年前
    public void createSpringLayout(SpringLayout spring, JLabel label, JScrollPane scrollPane, JPanel buttonPanel) {
        spring.putConstraint(SpringLayout.NORTH, label, 10, SpringLayout.NORTH, this);
        spring.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST, this);
    
        spring.putConstraint(SpringLayout.NORTH, scrollPane, 10, SpringLayout.SOUTH, label);
        spring.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, label);
        spring.putConstraint(SpringLayout.EAST, scrollPane, -10, SpringLayout.EAST, this);
    
        spring.putConstraint(SpringLayout.NORTH, buttonPanel, Spring.constant(10, 30, 30), SpringLayout.SOUTH, scrollPane);
    
        spring.putConstraint(SpringLayout.SOUTH, buttonPanel, -10, SpringLayout.SOUTH, this);
        spring.putConstraint(SpringLayout.WEST, buttonPanel, 0, SpringLayout.WEST, label);
    }
    

    This is what happens

    上面有所有东西的两个Jpanel使用相同的超类以获得更好的外观。 然而,正如您所看到的,如果滚动窗格的内容太宽,滚动窗格只会在底部使用额外的空间来创建水平滚动条。 即使我告诉Springlayout滚动窗格和按钮面板之间的弹簧可以在10到30之间。

    我认为,首先调用SpringLayoutManager来布局其组件,然后滚动窗格出现并注意到其显示的组件不适合视口,并创建了一个滚动条,而SpringLayoutManager对此一无所知。

    我找不到任何解决方案来提前告诉滚动窗格计算其所需的大小,或者让它从一开始就不使用更多的空间。

    1 回复  |  直到 2 年前
        1
  •  2
  •   VGR    2 年前

    不要将负数传递给 putConstraint .

    从…起 the documentation of putConstraint :

    将分量c1的边e1链接到分量c2的边e2,边之间具有固定距离。

    这个 pad 值不是绝对的像素偏移,而是组件和链接边之间的填充量(距离)。它应该总是积极的。

    相同的javadoc还描述了 衬垫 参数为:

    衬垫 -从属和锚点之间的固定距离

    SpringLayout很复杂,这意味着它很容易出错。您可以使用BorderLayout轻松完成相同的布局:

    setLayout(new BorderLayout());
    add(label, BorderLayout.PAGE_START);
    add(scrollPane, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.PAGE_END);
    
    label.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
    this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));