【发布时间】:2021-06-03 03:56:29
【问题描述】:
问题
我有一个JPanel 和GridBagLayout 作为布局管理器。我希望布局的列具有一定的宽度。有时一列的宽度可能低于内部组件的首选宽度。在这种情况下,列应强制组件仅占用列的可用空间。
但是,目前,如果列宽约束小于组件的首选宽度,则单元格内的组件不会缩小。
示例
以下是 4x4 网格的演示。我希望左上角的JLabel 按照我在初始化GridBagLayout (10 px) 时设置的最小宽度进行缩小
当我运行下面的例子时,得到以下结果:
左上角的单元格占用的空间比 GridBagLayout 最初允许的要多
public class ResizeDemo extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ResizeDemo resizeDemo = new ResizeDemo();
resizeDemo.pack();
resizeDemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
resizeDemo.setVisible(true);
});
}
public ResizeDemo() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
JPanel panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 0;
getContentPane().add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
// ============ Set the column widths here ============
// Note that the width of the first column is 10 px
gbl_panel.columnWidths = new int[] {10, 150, 0};
// =====================================================
gbl_panel.rowHeights = new int[]{0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0};
gbl_panel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel label1 = new JLabel("A very long string here");
label1.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_label1 = new GridBagConstraints();
gbc_label1.fill = GridBagConstraints.HORIZONTAL;
gbc_label1.gridx = 0;
gbc_label1.gridy = 0;
panel.add(label1, gbc_label1);
JLabel label2 = new JLabel("Label");
GridBagConstraints gbc_label2 = new GridBagConstraints();
gbc_label2.gridx = 1;
gbc_label2.gridy = 0;
panel.add(label2, gbc_label2);
JLabel label3 = new JLabel("Label");
GridBagConstraints gbc_label3 = new GridBagConstraints();
gbc_label3.fill = GridBagConstraints.HORIZONTAL;
gbc_label3.gridx = 0;
gbc_label3.gridy = 1;
panel.add(label3, gbc_label3);
JLabel label4 = new JLabel("Label");
GridBagConstraints gbc_label4 = new GridBagConstraints();
gbc_label4.gridx = 1;
gbc_label4.gridy = 1;
panel.add(label4, gbc_label4);
}
}
问题:
如何强制GridBagLayout 单元格内的JLabel 自行收缩?
【问题讨论】:
-
GridBagLayout 根据添加到列中的任何组件的最大“首选大小”来调整每列的大小。 “columnWidths”用于设置任何列的最小值。这在您调整框架大小时使用。如果没有足够的空间以首选大小显示组件,并且您为列设置了调整大小的权重,那么组件的大小将从首选大小缩小到最小大小。一种可能性是使用 BoxLayout 将标签包装在面板中。 BoxLayout 将遵循组件的最大尺寸。
标签: java swing jlabel layout-manager gridbaglayout