Java Swing How to - Position JPanel in the middle of the JFrame








Question

We would like to know how to position JPanel in the middle of the JFrame.

Answer

import java.awt.Dimension;
import java.awt.GridBagLayout;
/* w ww.j a  v a 2s  .  c o  m*/
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new MyContentPane());
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
  }
}

class MyContentPane extends JPanel {
  int PREF_W = 700;
  int PREF_H = 550;

  public MyContentPane() {
    setLayout(new GridBagLayout());
    add(new JPanelOfInterest());
  }

  @Override
  public Dimension getPreferredSize() {
    return new Dimension(PREF_W, PREF_H);
  }
}

class JPanelOfInterest extends JPanel {
  int PREF_W = 400;
  int PREF_H = PREF_W;

  public JPanelOfInterest() {
    setBorder(BorderFactory.createTitledBorder("Title"));
  }

  @Override
  public Dimension getPreferredSize() {
    return new Dimension(PREF_W, PREF_H);
  }
}