Search code examples
javaswingjtablejpanelpreferredsize

Adjusting JPanels to correct size


I have my code in this format, but the jpanels are not listening the size i set. All the three panels are in the same size when i run the code. Is there any way to adjust them?

JPanel mainpanel = new JPanel(mainPanel,BoxLayout.Y_AXIS);
JPanel tablepanel1 = new JPanel();
tablepanel1.setSize(900,400);
JPanel selectionpanel = new JPanel(new GridBagLayout());
selectionpanel.setSize(900,100);
JPanel tablepanel2 = new JPanel();
tablepanel2.setSize(900,400);

mainpanel.add(tablepanel1);
mainpanel.add(selectionpanel);
mainpanel.add(tablepanel2);

frame.add(mainpanel);
frame.setSize(900,900);

Solution

  • Did you mean to use BoxLayout for mainpanel?:

    JPanel mainpanel = new JPanel();
    mainpanel.setLayout(new BoxLayout(mainpanel, BoxLayout.Y_AXIS));
    

    This layout manager only listens to preferred sizes rather than the component size. The best way is to override getPreferredSize:

    JPanel selectionpanel = new JPanel() {
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(900, 400);
        }
    };
    

    Also better to use JFrame#pack rather than setting dimensions for the frame.