简体   繁体   中英

How do I make a button use up all of the space within a BorderLayout leaving no white space?

I've got a program which creates an 8x8 grid filled with random colours (already done this bit) and I'm supposed to add a button to the bottom which should fill the entire bottom part which will be used to reset the colours. I've already got the grid and the button, however, my button doesn't fill up the entire space at the bottom and only about half of it. How do I make it fill the entire space up?

My code:

public void createGUI() 
{
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Label demo");
    JPanel mainPanel = new JPanel();
    JPanel gridPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    JButton refreshButton = new JButton("Press me to refresh labels");
    mainPanel.setLayout(new BorderLayout());
    guiFrame.getContentPane().add(mainPanel);
    gridPanel.setLayout(new GridLayout(8, 8));
    for (int i = 0; i < arrayLabels.length; i++)
    {
        arrayLabels[i] = new ColorLabel(80, 80, new Color(rand.nextInt()), 0, new Color(rand.nextInt()));
    }

    for (int i = 0; i < 8*8; i++)
    {
        gridPanel.add(arrayLabels[i]);
    }
    guiFrame.getContentPane().add(gridPanel);
    buttonPanel.add(refreshButton);
    guiFrame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    guiFrame.setVisible(true);
}

And the output of my program currently is this: https://imgur.com/a/fw1Bx92

Also set the JPanel layout of refresh button! I make an example below you can examine it:

public static void createGUI() 
{
    JFrame guiFrame = new JFrame("a");
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiFrame.setTitle("Label demo");
    JPanel mainPanel = new JPanel();
    JPanel gridPanel = new JPanel();
    JPanel buttonPanel = new JPanel(new BorderLayout());
    JButton refreshButton = new JButton("Press me to refresh labels");
    mainPanel.setLayout(new BorderLayout());
    guiFrame.getContentPane().add(mainPanel);
    gridPanel.setLayout(new GridLayout(8, 8));
    JLabel arrayLabels[] = new JLabel[64];
    for (int i = 0; i < 64; i++)
    {
        arrayLabels[i] = new JLabel("a");
    }

    for (int i = 0; i < 8*8; i++)
    {
        gridPanel.add(arrayLabels[i]);
    }
    guiFrame.getContentPane().setLayout(new BorderLayout());
    guiFrame.getContentPane().add(gridPanel,BorderLayout.CENTER);
    buttonPanel.add(refreshButton,BorderLayout.CENTER);
    guiFrame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    guiFrame.setVisible(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM