Search code examples
javapositionjpaneljbutton

How to center buttons in a panel


Although I'm using BorderLayout.CENTER, my group of buttons still appears to be aligning to the north of the panel. If I use BorderLayout.SOUTH their relative position is the same as BorderLayout.CENTER but to the south of the panel.

How can I get them to be in the middle of the panel?

Is there anything I'm doing that is glaringly wrong?

public void createExecuteArea() {

      JButton connectButton = new JButton("Connect");
      connectButton.setPreferredSize(new Dimension(100, 40));
      JButton disconnectButton = new JButton("Disconnect");
      disconnectButton.setPreferredSize(new Dimension(100, 40));
      JButton abortButton = new JButton("Abort");
      abortButton.setPreferredSize(new Dimension(100, 40));

      executePanel = new JPanel();
      executePanel.setLayout(new BorderLayout());

      JPanel buttonPanel = new JPanel();

      buttonPanel.add(connectButton);
      buttonPanel.add(disconnectButton);
      buttonPanel.add(abortButton);

      executePanel.add(buttonPanel, BorderLayout.CENTER);
   }

The following changes to my code resolved my issues.

public void createExecuteArea() {

      JButton connectButton = new JButton("Connect");
      connectButton.setPreferredSize(new Dimension(100, 40));
      JButton disconnectButton = new JButton("Disconnect");
      disconnectButton.setPreferredSize(new Dimension(100, 40));
      JButton abortButton = new JButton("Abort");
      abortButton.setPreferredSize(new Dimension(100, 40));

      executePanel = new JPanel(new GridBagLayout());
      GridBagConstraints c = new GridBagConstraints();

      JPanel buttonPanel = new JPanel();

      buttonPanel.add(connectButton);
      buttonPanel.add(disconnectButton);
      buttonPanel.add(abortButton);

      executePanel.add(buttonPanel, c);
   }

Solution

  • The issue is with executePanel and what layout it is using. You don't give it an explicit layout, and so it uses a BorderLayout by default. If you want to center your buttons within this JPanel, then consider using a different layout, perhaps a GridBagLayout.

    For more specific help, consider creating and posting a minimal example program.