java - JPanels 不会完全拉伸(stretch)以占据可用空间

标签 java swing awt jpanel border-layout

我有一个面板,我在其中并排放置了几个尺寸和颜色不同的迷你面板,它们应该占据整个父面板(​​水平)。

为此,我使用 BorderLayout(用于父面板),并使用 BoxLayout 用于放置所有迷你面板的子面板(参见下面的代码)。它确实可以正常工作并且在调整大小和一切时都能正常运行。然而,随着迷你面板数量的增加,一个奇怪的行为发生了:父面板的末尾出现了空白。

enter image description here

我想我发现这是布局管理器中的一个拉伸(stretch)错误,因为为了拉伸(stretch)面板,布局管理器会尝试向每个迷你面板添加一个像素。但是,当 mini-panel 的数量很大时,为每个 mini-panel 添加一个像素将导致添加许多像素并超出父级的尺寸。因此,布局管理器最终不会向任何迷你面板添加任何像素,从而导致空白空间。

这是我的 SSCCE: (尝试运行并拉伸(stretch)窗口以了解问题)

package com.myPackage;

import java.awt.*;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ColoredPanels extends JPanel
{
    /* Content information. */
    private Vector<Integer> partitions;
    private Vector<Color> colors;

    /* Panel where the content panels will go. */
    private JPanel contentHolder;

    private final int defaultHeight = 20;

    public ColoredPanels(Vector<Integer> partitions, Vector<Color> colors)
    {
        assert partitions != null;
        assert !partitions.isEmpty();
        assert colors != null;
        assert !colors.isEmpty();
        assert colors.size() == partitions.size();

        this.partitions = partitions;
        this.colors = colors;

        /* Set layout manager. */
        setLayout(new BorderLayout());

        /* Create the content holder. */
        contentHolder = new JPanel();
        contentHolder.setLayout(new BoxLayout(contentHolder, BoxLayout.X_AXIS));
        this.add(contentHolder, BorderLayout.NORTH);

        /* Fill content holder with colored panels. */
        createPanels();
    }

    private void createPanels()
    {
        assert partitions != null;
        assert !partitions.isEmpty();
        assert colors != null;
        assert !colors.isEmpty();
        assert colors.size() == partitions.size();

        for (int i = 0; i < partitions.size(); i++)
        {
            JPanel newPanel = new JPanel();
            newPanel.setBackground(colors.get(i));
            newPanel.setPreferredSize(new Dimension(partitions.get(i), defaultHeight));
            newPanel.setMinimumSize(new Dimension(1, defaultHeight));
            contentHolder.add(newPanel);
        }
    }

    public static void main(String[] in)
    {
        Vector<Integer> sizes = new Vector<Integer>();
        Vector<Color> cols = new Vector<Color>();

        /* Make 100 random sizes, and use two colors. */
        for (int i = 0; i < 100; i++)
        {
            int size = (int)Math.round(1 + Math.random() * 10);
            sizes.add(size);
            cols.add((i%2 == 0)? Color.red : Color.green);
        }

        ColoredPanels panels = new ColoredPanels(sizes, cols);
        panels.setBorder(BorderFactory.createLineBorder(Color.yellow, 1));

        JFrame newFrame = new JFrame();
        newFrame.getContentPane().add(panels);
        newFrame.pack();
        newFrame.setVisible(true);
    }
}

如何避免这种行为?我希望我的面板占据整个容器。

编辑: 迷你面板旨在拥有(一旦解决)鼠标监听器。因此,不幸的是,绘画解决方案是可以避免的。

最佳答案

布局问题由 ... LayoutManagers 解决 :-) 如果您不希望它做什么,请实现您想要的行为。

因此,如果核心 BoxLayout 由于舍入错误而简单地忽略像素,请子类化并使其根据需要分配这些像素。一个非常原始的快速示例:

public static class XBoxLayout extends BoxLayout {

    enum Strategy {
        NONE,
        STRETCH_LAST,
        DISTRUBUTE
    }

    private Strategy strategy;

    public XBoxLayout(Container target, int axis, Strategy strategy) {
        super(target, axis);
        this.strategy = strategy;
    }


    @Override
    public void layoutContainer(Container target) {
        super.layoutContainer(target);
        if (Strategy.NONE == strategy) return;
        Insets targetInsets = target.getInsets();
        int targetSize = target.getWidth() - targetInsets.left - targetInsets.right;
        int childSum = 0;
        for (Component child : target.getComponents()) {
            childSum += child.getWidth();
        }
        if (targetSize > childSum) {
            int excess = targetSize - childSum;
            distribute(target, excess);
        }
    }


    private void distribute(Container target, int excess) {
        System.out.println("childCount/rounding excess " + target.getComponentCount() + "/" + excess);
        if (Strategy.STRETCH_LAST == strategy) {
            Component lastChild = target.getComponent(target
                    .getComponentCount() - 1);
            lastChild.setSize(lastChild.getWidth() + excess,
                    lastChild.getHeight());
        } else {
            int firstToDistribute = target.getComponentCount() - excess;
            int summedOffset = 0;
            for(int index = firstToDistribute; index < target.getComponentCount(); index++) {
                Component child = target.getComponent(index);
                Rectangle bounds = child.getBounds();
                bounds.x += summedOffset++;
                bounds.width += 1;
                child.setBounds(bounds);
            }
        }
    }

}

关于java - JPanels 不会完全拉伸(stretch)以占据可用空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212989/

相关文章:

java - 如何用简单的消息随机设置 JFrame

java - Firebase 突然停止工作,找不到 com.google.android.gms.crash 的本地模块描述符类

java - Color.RED(大写)和 Color.red 有什么区别?

java - JLabel 上的选项卡空间未显示 - 奇怪 - Java

java - Java中如何使字体适合像素大小?如何将像素转换为点?

java - 使用 Objects.hash() 还是自己的 hashCode() 实现?

java - CompletableFuture 链未调用 thenAcceptAsync

java - Java 中的多线程,我希望 UI 和代码并行执行

Java Swing : how to customize the JList's items?

java - Rectangle.intersection(Rectangle) 返回宽度和高度为负的矩形