java 设置 JScrollPane 的恒定大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14169141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:20:06  来源:igfitidea点击:

Set constant size of JScrollPane

javajscrollpanelayout-managerjtabbedpaneborder-layout

提问by Joel Christophel

I have a JTabbedPane with a Border Layout.

我有一个带有边框布局的 JTabbedPane。

enter image description here

在此处输入图片说明

Here's the code I'm using to add the components:

这是我用来添加组件的代码:

add(columnNames, BorderLayout.NORTH);
add(scroll, BorderLayout.CENTER);
add(useCtrl, BorderLayout.SOUTH);
setVisible(true);

Question: Notice the excess whitespace to the right inside the JScrollPane. I don't want that there. I would like for the JScrollPane not to change size at all when changing the size of the JFrame. I have tried setSize() and setPreferredSize(), but the size of the JScrollPane always changes. I've tried using GridLayout, but I get the same result.

问题:注意 JScrollPane 右侧的多余空白。我不想在那里。我希望 JScrollPane 在更改 JFrame 的大小时根本不更改大小。我尝试过 setSize() 和 setPreferredSize(),但 JScrollPane 的大小总是在变化。我试过使用 GridLayout,但我得到了相同的结果。

回答by StanislavL

Place the JScrollPanein a JPanelwith another layout. (e.g. BoxLayoutor GridBagLayout). And add the JPanelto the center.

将与另一个布局JScrollPane放在JPanel一起。(例如BoxLayoutGridBagLayout)。并添加JPanel到中心。

回答by Mel Nicholson

The size of a graphics object is controlled by the layout manager. The BorderLayoutwill always expand the CENTERobject to take up all available space. GridLayoutexpands all it's children proportionally. If you try a GridBagLayout and set the weightxto 0, that will prevent expansion horizontally.

图形对象的大小由布局管理器控制。该BorderLayout会一直扩大CENTER对象占用全部可用空间。 GridLayout按比例扩展它的所有子项。如果您尝试使用 GridBagLayout 并将 设置weightx为 0,则将阻止水平扩展。

There are a lot of layout managers available, browse the API for more choices and experiment until you find the resizing behavior you want. Each has a fairly good explanation of how it works in the javadoc.

有很多可用的布局管理器,浏览 API 以获得更多选择并进行试验,直到找到所需的调整大小行为。每个人都对它在 javadoc 中的工作方式有很好的解释。