Swing组件-禁用布局大小调整 [英] Swing Component - disabling resize in layout
问题描述
我有一个基于Swing的JPanel的自定义GUI组件.该组件放置在使用BorderLayout的JFrame中.当我调整框架大小时,此组件会不断调整大小.如何避免这种情况?无论发生什么情况,我都希望组件保持相同的大小.我尝试了setSize,setPreferredSize,setMinimumSize,但没有成功.
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.
提前谢谢!
M
推荐答案
您有一些选择:
-
使用
LayoutManager
将组件嵌套在内部面板中,该组件不调整组件的大小
Nest the component in an inner panel with a
LayoutManager
that does not resize your component
使用比BorderLayout
更复杂的LayoutManager.在我看来,GridBagLayout
在这里会更适合您的需求.
Use a more sophisticated LayoutManager than BorderLayout
. Seems to me like GridBagLayout
would suit your needs better here.
第一个解决方案的示例:
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);
}
}
结果:
绿色组件放置在BorderLayout.CENTER
中,红色组件保持首选大小.
Green component placed in BorderLayout.CENTER
, red component maintains preferred size.
这篇关于Swing组件-禁用布局大小调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!