Java Swing布局问题

标签 java swing layout jpanel

我正在使用 Java 和 Swing 库设计一个应用程序(我也可以使用 AWT 的片段),并且我需要一些有关“自定义”布局的帮助。

我有一个大的 JScrollPanel,我将在其中动态插入可变高度的 JPanel。这是一个或多或少真实的绘图:

|-------------------------------- JScrollPane ------------------------------|
| |------------------------------- JPanel --------------------------------| |
| |                                                                       | |
| |-----------------------------------------------------------------------| |
|                                                                           |
| |------------------------------- JPanel --------------------------------| |
| |                                                                       | |
| |                                                                       | |
| |-----------------------------------------------------------------------| |
|                                                                           |
|---------------------------------------------------------------------------|

然后我不知道使用哪个布局......我希望 mainLayout 不调整内部 JPanel 的高度,而是调整其宽度。因此,例如,当我扩展窗口时,我希望内部布局保持靠近左右边框,但不要垂直扩展。

有什么建议吗?

我希望我的英语和解释不太糟糕。 感谢您的阅读!

最佳答案

在这种情况下我可能使用的布局是 GridBagLayoutVerticalLayout (来自 SwingLabs、SwingX 库)(但是当你只有锤子时,一切看起来都像一个钉子;))。

要使用GridBagLayout,您需要提供适当的约束来指示布局管理器水平填充面板,但要遵守高度。

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;

唯一的问题是 GridBagLayout 喜欢将其组件集中在父容器的中心位置周围。您可能需要在占用剩余垂直空间的最后一个位置添加一个“填充”组件

gbc.weighty = 1;

应该够了

看看How to use GridBagLayout了解更多详情

使用非常基本的示例进行更新...

// Basic constraints...
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;

// Add your components...
add(panel, gbc);
//...

// Then add a fill component to push the layout to the top...
gbc.weighty = 1;
add(new JPanel(), gbc);
// You can use a constant value if you want, as it will be easier to remove
// so you can add new components to the end and re-add it when you're done

关于Java Swing布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19848249/

相关文章:

java - 如何调用具有消息安全和客户端证书认证的Web安全?

Java异步订单

java - 低延迟网络技术和银弹

java - 如何在android中以编程方式查找网络上其他WiFi设备的IP地址

java - 如何在Java中使用信号量

php - PHP switch语句的最佳布局?

android - 如何从 android 中的 string.xml 读取值?

java - 使用 JButton 作为图像

java - 如何将 ctrl+f 添加到 java swings JFrame

Android:设置 ALIGN_PARENT_RIGHT 不起作用