Search code examples
javaswingjpanelgrid-layoutboxlayout

Java Swing making boxes with custom dimensions


I need help making a layout in Java Swing. My boxes are coming out to be really small and can't figure out how to make them bigger.

Here is what it looks like: https://i.sstatic.net/acRjl.png

enter image description here

And here is what I want: https://i.sstatic.net/yoja3.png

enter image description here

Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MPC
{
    public static void main(String [] args)
    {
            createWindow();
    }

    public static void createWindow()
    {
            JPanel main, left, right;
            JFrame frame = new JFrame("MPC");
            Box [] box = new Box[16];
            JSlider tempo = new JSlider(JSlider.VERTICAL, 0, 30, 15);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            main = new JPanel();
            main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

            //Left side holds boxes
            left = new JPanel();
            left.setLayout(new GridLayout(4, 4));

            for(int i = 0; i < 16; i++)
            {
                    box[i] = new Box(BoxLayout.X_AXIS);
                    box[i].setBorder(BorderFactory.createLineBorder(Color.black));
                    box[i].add(new JLabel("      " + (i+1) + "      "));
                    left.add(box[i]);
            }

            //Right side for tempo
            right = new JPanel();
            right.setLayout(new GridLayout(1, 1));
            tempo.setMajorTickSpacing(10);
            tempo.setMinorTickSpacing(1);
            tempo.setPaintTicks(true);
            right.add(tempo);

            //Add everything to window
            main.add(left, BorderLayout.WEST);
            main.add(right, BorderLayout.EAST);

            frame.add(main);
            frame.getContentPane();

            //Window Stuff
            frame.setBounds(50,50,500,500);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }
}

What can I do to make it look like the second picture? Any help would be appreciated!


Solution

  • Try changing the layout of main to BorderLayout:

    main = new JPanel(new BorderLayout());
    

    Then, add add left panel to the center of BorderLayout

    main.add(left, BorderLayout.CENTER);
    

    This way the grid of boxes will occupy as much of the available space of main as possible. See How to Use BorderLayout for more details.

    Result with these changes:

    enter image description here