java Swing 组件 - 在布局中禁用调整大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6492794/
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
Swing Component - disabling resize in layout
提问by Michael
I have a custom GUI compomemt, which is based on Swing's JPanel. This component is placed in a JFrame, that uses BorderLayout. When I resize the frame, this component keeps resizing. How can I avoid this? I would like the component to keep the same size whatever happens. I've tried setSize, setPreferredSize, setMinimumSize with no success.
我有一个基于 Swing 的 JPanel 的自定义 GUI 组件。此组件放置在使用 BorderLayout 的 JFrame 中。当我调整框架大小时,此组件会不断调整大小。我怎样才能避免这种情况?无论发生什么,我都希望组件保持相同的大小。我试过 setSize、setPreferredSize、setMinimumSize 都没有成功。
Thanks in advance!
提前致谢!
M
米
回答by aioobe
You have a few options:
您有几个选择:
Nest the component in an inner panel with a
LayoutManager
that does notresize your componentUse a more sophisticated LayoutManager than
BorderLayout
. Seems to me likeGridBagLayout
would suit your needs better here.
巢内板组件用
LayoutManager
,它不调整你的组件使用比
BorderLayout
. 在我看来,GridBagLayout
这里更适合您的需求。
Example of the first solution:
第一个解决方案的示例:
import java.awt.*;
import javax.swing.*;
public class FrameTestBase extends JFrame {
public static void main(String args[]) {
FrameTestBase t = new FrameTestBase();
JPanel mainPanel = new JPanel(new BorderLayout());
// Create some component
JLabel l = new JLabel("hello world");
l.setOpaque(true);
l.setBackground(Color.RED);
JPanel extraPanel = new JPanel(new FlowLayout());
l.setPreferredSize(new Dimension(100, 100));
extraPanel.setBackground(Color.GREEN);
// Instead of adding l to the mainPanel (BorderLayout),
// add it to the extra panel
extraPanel.add(l);
// Now add the extra panel instead of l
mainPanel.add(extraPanel, BorderLayout.CENTER);
t.setContentPane(mainPanel);
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setSize(400, 200);
t.setVisible(true);
}
}
Result:
结果:
Green component placed in BorderLayout.CENTER
, red component maintains preferred size.
放置在 中的绿色组件BorderLayout.CENTER
,红色组件保持首选大小。
回答by Abdul
//this will restrict size on fix size, what ever size you will define for panel like
//panel.setSize(400,400);
panel.setMaximumSize(panel.getSize());
panel..setMinimumSize(panel.getSize());
回答by Boldbayar
if you are using custom layout manager, change your current layout to GridBagLayout and change fill options to NONE, after that change it back to your first layout.
如果您使用自定义布局管理器,请将当前布局更改为 GridBagLayout 并将填充选项更改为NONE,然后将其更改回您的第一个布局。