我无法理解我的应用程序的行为。我想创建一个简单的窗口 (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
而不是使用add()
使用 BorderLayout.EAST
的方法和 BorderLayout.WEST
参数,但我想了解 FlowLayout
有什么问题.
当我运行我的应用程序时,我得到以下信息(没有绿色 JPanel
):
如果我减小宽度,例如 content_panel_wrap
并将其设置为 744px 而不是 750px,一切正常。
所以问题是——这些奇怪的 6 个像素是什么?我不确定这个值对于所有操作系统都是不变的,所以我想了解它的来源。
最佳答案
FlowLayout
没有问题,但您需要调用 pack()
来调整所有组件的大小。
关于Java Swing : problems with width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053919/