BorderLayout中FlowLayout换行覆盖JTextArea,如何实现JTextArea自适应?
解决FlowLayout换行时覆盖JTextArea的问题
问题原因
默认的FlowLayout在组件换行后,容器的首选高度不会自动更新,导致BorderLayout无法感知顶部面板需要更多垂直空间,进而让顶部面板溢出并覆盖下方的JTextArea区域。
解决方案
推荐使用改进版的WrapLayout(FlowLayout子类),它能正确计算换行后的容器首选高度,让BorderLayout自动调整各区域的大小。
第一步:实现WrapLayout
import java.awt.*; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; public class WrapLayout extends FlowLayout { public WrapLayout() { super(); } public WrapLayout(int align) { super(align); } public WrapLayout(int align, int hgap, int vgap) { super(align, hgap, vgap); } @Override public Dimension preferredLayoutSize(Container target) { return layoutSize(target, true); } @Override public Dimension minimumLayoutSize(Container target) { Dimension dim = layoutSize(target, false); dim.width -= (getHgap() + 1); return dim; } private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { int targetWidth = target.getSize().width; if (targetWidth == 0) { targetWidth = Integer.MAX_VALUE; } int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); if (scrollPane != null) { dim.width -= (hgap + 1); } return dim; } } private void addRow(Dimension dim, int rowWidth, int rowHeight) { dim.width = Math.max(dim.width, rowWidth); if (dim.height > 0) { dim.height += getVgap(); } dim.height += rowHeight; } }
第二步:修改原代码的布局
把顶部JPanel的FlowLayout替换成WrapLayout:
// 原代码 // JPanel jPanel = new JPanel(new FlowLayout()); // 修改为: JPanel jPanel = new JPanel(new WrapLayout());
效果
窗口缩小时,顶部面板换行后会自动扩展高度,BorderLayout会自动调整CENTER区域的JTextArea大小,避免被覆盖。
内容的提问来源于stack exchange,提问作者nobody
相关产品推荐
相关产品推荐

