我有一个自定义 GUI 组件,它基于 Swing 的 JPanel。该组件放置在使用 BorderLayout 的 JFrame 中。当我调整框架大小时,该组件会不断调整大小。我怎样才能避免这种情况?我希望组件无论发生什么情况都保持相同的大小。我尝试过 setSize、setPreferredSize、setMinimumSize 但没有成功。
提前致谢!
M
您有几个选择:
第一个解决方案的示例:
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:
绿色组件放置在BorderLayout.CENTER
,红色分量保持首选大小。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)