【发布时间】:2012-10-24 16:53:04
【问题描述】:
我无法理解我的应用程序的行为。我想创建一个简单的窗口(1000x700px),分为两部分(分别为 250px 和 750px 宽度)。我尝试了以下代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example extends JFrame
{
private static final long serialVersionUID = 1L;
public Example()
{
this.setSize(1000, 700);
this.setTitle("Example");
this.setResizable(false);
this.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
JPanel navigation_panel_wrap = new JPanel();
JPanel content_panel_wrap = new JPanel();
navigation_panel_wrap.setPreferredSize(new Dimension(250, 700));
content_panel_wrap.setPreferredSize(new Dimension(750, 700));
content_panel_wrap.setBackground(Color.green);
navigation_panel_wrap.setBackground(Color.red);
this.getContentPane().add(navigation_panel_wrap);
this.getContentPane().add(content_panel_wrap);
}
public static void main(String[] args)
{
Example example = new Example();
example.setVisible(true);
}
}
如您所见,我为JFrame 手动设置了布局管理器(FlowLayout 而不是BorderLayout,水平和垂直间隙为零)。当然,我可以只使用BorderLayout 而不是使用带有BorderLayout.EAST 和BorderLayout.WEST 参数的add() 方法,但我想了解FlowLayout 有什么问题。
当我运行我的应用程序时,我得到以下信息(没有绿色 JPanel):
如果我减小例如content_panel_wrap 的宽度并将其设为 744px 而不是 750px,则一切正常。
所以问题是 - 这些奇怪的 6 个像素是什么?我不确定这个值对于所有操作系统都是恒定的,所以我想了解它的来源。
【问题讨论】:
-
看到这个Q&A。
-
非常感谢,非常有用的链接。
标签: java swing layout layout-manager preferredsize