Swing JPanel布局管理器

时间:2016-01-31 10:23:27

标签: java swing

这应该很简单,不知道为什么我没有得到它。我尝试使用GroupLayout在JFrame(mainWindow)中创建JPanel。我希望面板能够覆盖整个框架的宽度,但是面板的宽度/高度保持为0(即使框架加载并且面板覆盖了所有框架)。谁能帮我?不确定我错过了什么。

panel = new JPanel();
Container pane = mainWindow.getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(false);
gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(panel));
gl.setVerticalGroup(gl.createSequentialGroup().addComponent(panel));
// panel.getWidth() and panel.getHeight() both return 0 here

1 个答案:

答案 0 :(得分:1)

panel = new JPanel();
Container pane = mainWindow.getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(false);
gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(panel));
gl.setVerticalGroup(gl.createSequentialGroup().addComponent(panel));
// ++++++++++++  editing start
// force do layout subcomponents and rendering
mainWindow.pack();
// ++++++++++++  editing end
System.out.println("w:" + panel.getWidth() + " h:" + panel.getHeight());