我有一个面板,我在其中并排放置了几个具有不同尺寸和颜色的迷你面板,它们应该占据整个父面板(水平)。
为此,我使用 BorderLayout(用于父面板)和 BoxLayout 用于放置所有迷你面板的子面板(参见下面的代码)。它确实可以在调整大小和所有内容时正常工作并正常运行。然而,随着迷你面板的数量变大,出现了一个奇怪的行为:父面板的末尾出现空白。
我想我发现这是布局管理器中的一个拉伸错误,因为为了拉伸面板,布局管理器尝试向每个迷你面板添加一个像素。但是,当 mini-panel 的数量很大时,每个都添加一个像素会导致添加许多像素并超出父级的大小。因此,布局管理器最终不会向任何迷你面板添加任何像素,从而导致空白空间。
这是我的 SSCCE:(尝试运行并拉伸窗口以了解问题)
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);
}
}
我该如何避免这种行为?我希望我的面板占据整个容器。
编辑: 迷你面板旨在拥有(一旦解决)鼠标侦听器。因此,不幸的是,油漆解决方案是可以避免的。