这个问题可能已经在这里得到解答,但我的搜索却一片空白,也许我正在寻找错误的东西。
如何阻止 JTextArea
和 JTextField
拉伸(stretch)? swing 是否提供了某种类型的面板垫片,我可以添加该垫片,该垫片将在任何其他元素之前被拉伸(stretch)?
我有一个JPanel
,它用设定的大小填充JFrame
。它使用设置为 PAGE_AXIS
的 BoxLayout
。如果我添加一个大小为 3,100 的 JTextArea
,它将忽略这些行/列大小并填充所有可用空间。
同样,我有一个带有 GridLayout
的 JPanel
。如果我添加一个 JTextField
,而不是我指定的列大小,它会填充网格中的整个空间。
最佳答案
直接来自 How to Use GridLayout 的文档中的几句话
A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container.
GridLayout
不考虑组件的大小。它尝试将组件放入行和列的可用空间中。
尽量避免明确设置大小。有一篇关于Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?的非常好的帖子这可以帮助您以更好的方式设计它。
有很多布局管理器可以满足您的要求。请查看How to Use Various Layout Managers
您可以使用GridBagLayout
而不是 GridLayout
将组件划分为行和列,就像表格布局一样,让您可以更好地控制网格宽度、高度、边距、填充、列、行等。
关于java - 如何阻止 JTextArea 和 JTextField 拉伸(stretch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36642055/