Search code examples
javaswinglayout-managerborder-layoutflowlayout

Not able to display all Buttons on JFrame


Below is my code. I am not able to add all the 6 buttons. Only Button1 - 3 or Button4-6 are getting displayed at a time.

Kindly let me know where I am going wrong.

// This class contains the main method and launches the Main screen 
import javax.swing.*;
import java.awt.*;

public class LearningHome{
    public static void main(String[] args){
        JFrame mainFrame = new JFrame("Welcome to the Learning! ");

        try {

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(800, 800);
        mainFrame.setVisible(true); // Without this property the frame will not be visible

        FlowLayout mainLayout = new FlowLayout();
        JPanel mainPanel = new JPanel();

        mainPanel.setLayout(mainLayout);

        mainPanel.add(new JButton(" Button 1 "));
        mainPanel.add(new JButton(" Button 2 "));
        mainPanel.add(new JButton(" Button 3 "));

        JPanel subPanel = new JPanel();

        subPanel.setLayout(mainLayout);

        subPanel.add(new JButton(" Button 4 "));
        subPanel.add(new JButton(" Button 5 "));
        subPanel.add(new JButton(" Button 6 "));

        mainFrame.add(mainPanel, mainLayout.LEFT);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.add(subPanel, mainLayout.RIGHT);
    }
}

Solution

  • You did not mention the exact layout you seek, and there is a wide number of way to go about arranging components, but to address your specific comment

    I am not able to add all the 6 buttons. Only Button1 - 3 or Button4-6 are getting displayed at a time

    1. Add all elements to the JFrame before it becomes visible (eg. move the mainFrame.setVisible(true) after you add components to mainFrame. This way the LayoutManager can arrange the components as needed
    2. Consider calling mainFrame.pack(); prior to calling setVisible (see What does .pack() do? )
    3. The default LayoutManager for the content pane of a JFrame is BorderLayout (default for a JPanel is FlowLayout - so no need to explicitly set the Layout as such)...if you wish to add the two panels so they layout in a line, consider using an appropriate combination of BorderLayout parameters.

    For example:

    mainFrame.add(mainPanel, BorderLayout.WEST);
    mainFrame.add(mainPanel, BorderLayout.EAST);
    mainFrame.pack();//call these methods after adding components
    mainFrame.setVisible(true);
    

    You can alternatively stack them into two lines using the appropriate BorderLayout parameters. For example:

    mainFrame.add(mainPanel, BorderLayout.CENTER);
    mainFrame.add(mainPanel, BorderLayout.SOUTH);