Search code examples
javaswinglayoutcenterlayout-manager

How to center a JPanel (that contains a JBox, but not necessarily)?


I've been searching for about 2 hours, and reading methods and tutorials, but for some reason my program still doesn't behave as expected.

I want to put that panel which contains a box which contains some buttons in the center of the screen. There is a way to do it with RigidBox but it's hard-coded to the size of my current window/screen, and I'd like something that would be centered regardless of where it's opened from.

    package layout;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;

import javax.swing.*;

public class Layout2 {

    public static void main(String[] args) {

        //The window that opens when you run the application
        JFrame mainWindow = new JFrame("Solitare Anca Version 2016");
        mainWindow.setSize(1000, 800);
        mainWindow.setLocation(460, 140);

        //The main menu bar, default in top left of the window it belongs to I think?
        JMenuBar mainMenu = new JMenuBar();
        //JMenu's=the menus in a bar
        JMenu file = new JMenu("Home");
        //Items in each menu
        JMenuItem save=new JMenuItem("Save progress");
        file.add(save);
        JMenuItem load=new JMenuItem("Load game");
        file.add(load);
        JMenuItem savexit=new JMenuItem("Save & exit");
        file.add(savexit);
        JMenuItem close=new JMenuItem("Close game");
        file.add(close);
        JMenu options = new JMenu("Options");
        JMenuItem changeback=new JMenuItem("Pick another card back");
        options.add(changeback);
        JMenuItem changecolor=new JMenuItem("Modify background color");
        options.add(changecolor);
        JMenuItem changelang=new JMenuItem("Change language");
        options.add(changelang);
        JMenuItem sound=new JMenuItem("Sound options");
        options.add(sound);
        JMenu help = new JMenu("Help");
        JMenuItem rules=new JMenuItem("Rules");
        help.add(rules);

        //Ading the menus to the bar
        mainMenu.add(file);
        mainMenu.add(options);
        mainMenu.add(help);

        JPanel content=new JPanel();

        JPanel butPan = new JPanel();
        butPan.setBackground(Color.BLACK);

        JButton okbut = new JButton("START THE GAME");
        JButton exitbut = new JButton("   EXIT   ");
        Box butBox=Box.createVerticalBox();
        butBox.add(okbut);
        butBox.add(exitbut);
        butPan.add(BorderLayout.SOUTH, butBox);


        //Set bg of the main window to the very familiar default green
        content.setBackground(Color.decode("#008001")); 
        content.add(BorderLayout.SOUTH,butPan);

        mainWindow.setJMenuBar(mainMenu);
        mainWindow.setContentPane(content);
        mainWindow.setVisible(true);

        // mainWindow.setContentPane(content);

    }

}

Here I was just trying different ways to move that damned panel/box but it just won't budge...


Solution

  • Here are four ways to center a component:

    4 Centered Components

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    class CenterComponent {
    
        public static JLabel getLabel(String text) {
            return getLabel(text, SwingConstants.LEFT);
        }
    
        public static JLabel getLabel(String text, int alignment) {
            JLabel l = new JLabel(text, alignment);
            l.setBorder(new LineBorder(Color.RED, 2));
            return l;
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JPanel p = new JPanel(new GridLayout(2,2,4,4));
                    p.setBackground(Color.black);
                    p.setBorder(new EmptyBorder(4,4,4,4));
    
                    JPanel border = new JPanel(new BorderLayout());
                    border.add(getLabel(
                        "Border", SwingConstants.CENTER), BorderLayout.CENTER);
                    p.add(border);
    
                    JPanel gridbag = new JPanel(new GridBagLayout());
                    gridbag.add(getLabel("GridBag"));
                    p.add(gridbag);
    
                    JPanel grid = new JPanel(new GridLayout());
                    grid.add(getLabel("Grid", SwingConstants.CENTER));
                    p.add(grid);
    
                    // from @0verbose
                    JPanel box = new JPanel();
                    box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));
    
                    box.add(Box.createHorizontalGlue());
                    box.add(getLabel("Box"));
                    box.add(Box.createHorizontalGlue());
                    p.add(box);
    
                    JFrame f = new JFrame("Streeeetch me..");
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setContentPane(p);
                    f.pack();
                    f.setLocationByPlatform(true);
                    f.setVisible(true);
                }
            });
        }
    }