Search code examples
javapanelgridbaglayout

JFrame laying out multiple JPanels


The Panel I am making

I am not sure how I could create a panel like this. I could have the main panel as a borderlayout and set the login screen panel to the page_end but then the forums and faqs also have to be on the page_end..... somehow the login screen panel and the forums and faqs panel has to share the page_end together. Is there someway I could do this or maybe some BETTER way? This has been confusing me for about 2 hours and I don't understand how I would do this.

Right now I have 3 panels and 1 frame. 1 is the main panel that is added to the main frame. The 2 other panels are the loginscreen panel and the forums and faqs panel. Here is the code.

    private void createView() {

    //Created essential details for the frame
    JFrame frame = new JFrame();
    frame.setTitle("Name of the game");
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Defining layouts and panels + giving them layouts
    JPanel pMain = new JPanel();
    frame.getContentPane().add(pMain);
    pMain.setLayout(new BorderLayout());

    JPanel pLogin = new JPanel(new GridBagLayout());
    pMain.add(pLogin, BorderLayout.PAGE_END);
    JPanel pInfo = new JPanel(new GridBagLayout());
    pMain.add(pInfo, BorderLayout.PAGE_END);

    frame.setVisible(true);

}

Solution

  • Here is the component layout

    Source

            JFrame frame = new JFrame();
            frame.setTitle("Name of the game");
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            // Defining layouts and panels + giving them layouts
            JPanel pMain = new JPanel();
            frame.getContentPane().add(pMain);
            pMain.setLayout(new BorderLayout());
    
            JPanel bottomComponentsPanel = new JPanel(new GridBagLayout());
    
            JPanel pLogin = new JPanel();
            pLogin.setBackground(Color.ORANGE);
            pLogin.setPreferredSize(new Dimension(100, 100));
    
            JPanel pInfo = new JPanel(new GridBagLayout());
            pInfo.setBackground(Color.ORANGE);
            pInfo.setPreferredSize(new Dimension(70, 70));
    
            GridBagConstraints constraints = new GridBagConstraints();
            constraints.anchor = GridBagConstraints.PAGE_END;
            constraints.gridx = 0;
            constraints.gridy = 0;
    
            bottomComponentsPanel.add(pLogin, constraints);
    
            constraints.gridx = 1;
            constraints.gridy = 0;
            bottomComponentsPanel.add(pInfo, constraints);
    
            JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    
            bottomPanel.add(bottomComponentsPanel);
    
            pMain.add(bottomPanel, BorderLayout.SOUTH);
    
            frame.setVisible(true);
    

    Display

    enter image description here