java - 不正确的 GridBagLayout 行为

标签 java swing jscrollpane layout-manager gridbaglayout

当我调整 JFrame 大小时,表格(或更具体地说是scrollPane)会压缩成一个小矩形(保持不变,但高度更像是 5-10 像素)。

我还注意到 JFrame 有一个特定的高度阈值,当 JFrame 的高度低于此阈值时,所有 GridBagLayout 都会正常运行(例如,所有面板的宽度和高度正确)。当高度高于此阈值时,两个右侧面板都会获得额外的宽度,并且在降低 JFrame 高度时,rightTopPanel 比 rightBottomPanel 失去高度的速度要快得多。

阈值似乎是 rightTopPanel 获得最小高度(大约 5-10 像素)时的点。

JPanel panel = new JPanel(new GridBagLayout());

JPanel rightTopPanel = new JPanel(new GridBagLayout());
panel.add(rightTopPanel, Helper.createGridBagConstraints(1, 0, 1, 1, 0.5, 0.5, GridBagConstraints.BOTH));

JPanel rightBottomPanel = new JPanel(new GridLayout(1, 1));

tableModel = new DefaultTableModel(0, 2);
JTable table = new JTable(tableModel);

JScrollPane scrollPane = new JScrollPane(table);
rightBottomPanel.add(scrollPane);

panel.add(rightBottomPanel, Helper.createGridBagConstraints(1, 1, 1, 1, 0.5, 0.5, GridBagConstraints.BOTH));

JPanel leftPanel = new JPanel();
panel.add(leftPanel, Helper.createGridBagConstraints(0, 0, 1, 2, 0.5, 1.0));

add(panel);

Helper.createGridBagConstraints 只是创建 GridBagConstraints 的辅助方法,具有许多“可选”参数。

GridBagConstraints createGridBagConstraints(int gridx, int gridy)
GridBagConstraints createGridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight)
GridBagConstraints createGridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty)
GridBagConstraints createGridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int fill)

编辑:这似乎是 JScrollPane 中的问题。如果我不添加它,其余面板会正确调整大小。

编辑2:由于到目前为止没有人明白我的问题是什么,以下是屏幕截图: http://img155.imageshack.us/img155/8847/badgridbaglayout1.png

http://img17.imageshack.us/img17/8779/badgridbaglayout2.png

http://img28.imageshack.us/img28/9336/badgridbaglayout3.png

最佳答案

the table (or more specifically the scrollPane) squishes into a little rectangle (with remains the same, but height is more like 5-10 pixels).

GridBagLayout 将尝试按照组件的首选大小绘制组件。当框架缩小时,组件将以“最小尺寸”绘制。因此有时组件的最小尺寸为 0,它只会显示为一个小矩形。

您可以尝试将滚动 Pane 的最小大小设置为等于首选大小,或者您可以使用您使用的约束来控制此行为。

阅读 Swing 教程中关于 How to Use GridBagLayout 的部分了解更多信息。

如果您仍然遇到问题,请发布您的 SSCCE这说明了问题。

关于java - 不正确的 GridBagLayout 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6571089/

相关文章:

java - 如何提高 JScrollPane 的慢速滚动速度?

Java:如何应用过滤器来设置?

java - GRPC 连接状态监听器 Java

java - 安卓数独游戏,按下按钮使游戏崩溃

java - 如何使用 Netbeans 在 JFrame 中显示文本?如何清除 JFrame 中的文本?

java - JLabel.setIcon() 无法按预期工作

Xmonad 中不显示 Java Swing GUI

java - JPanel inside JScrollPane 绘画问题

java - 如何在 Java 应用程序中播放 ALAW 文件?

java - 为什么我要在这个例子中使用 JScrollPane ?