0

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
geco17
  • 5,152
  • 3
  • 21
  • 38
  • 1
    Any reason you're using `GroupLayout` and not something like `BorderLayout` or `GridBagLayout` or `GridLayout`? – MadProgrammer Jan 31 '16 at 10:56
  • [possible duplicate](http://stackoverflow.com/questions/6999794/java-jframe-getwidth-returns-0) – guleryuz Jan 31 '16 at 11:15
  • Thanks @MadProgrammer, I overcomplicated it initially. BorderLayout was fine and I forgot to pack the frame. – geco17 Jan 31 '16 at 11:32

1 Answers1

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());
guleryuz
  • 2,714
  • 1
  • 15
  • 19
  • 2
    You should explain what is different from the original version, and why your change solves the problem. Code-only answers should be very, very self-evident to be good anwers - otherwise, add explanations! – tucuxi Jan 31 '16 at 11:15
  • JPanel (panel = new JPanel();) has FlowLayout (default in API), then (without JComponent added there) can returns zero Dimension ( 0, 0 ), GroupLayout accepts that – mKorbel Jan 31 '16 at 12:09