geco17
geco17

Reputation: 5294

Swing JPanel layout manager

This should be simple, not sure why I'm not getting it. I'm trying to create a JPanel inside a JFrame (mainWindow) with GroupLayout. I want the panel to cover the width of the whole frame, which it does, but the panel's width / height remain 0 (even though the frame loads and the panel covers all of it). Can anyone help me? Not sure what I'm missing.

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

Upvotes: 0

Views: 74

Answers (1)

guleryuz
guleryuz

Reputation: 2734

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());

Upvotes: 1

Related Questions