1

How can I put my JPanel in the center of a JFrame without using a layout manager? I want it to be generic for all screen resolutions of course.

Thanks, Tomer

tomericco
  • 1,544
  • 3
  • 19
  • 30
  • I think its a very simple procedure. But I will be happy if anyone will tell me how can I center a JPanel in a JFrame, with or without layout managers. Thanks. – tomericco Feb 04 '11 at 09:35

1 Answers1

-2

If you don't use layouts (setLayout(null)), you need to calculate the location of the JPanel inside the JFrame, like:

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

public class a extends JFrame {

public a()
{
    JPanel panel = new JPanel();
    panel.setSize(200, 200);
    panel.setBackground(Color.RED);
    setSize(400, 400); // JFrame arbitrary size.
    getContentPane().setLayout(null);
    getContentPane().add(panel);
    setVisible(true);
    // Caculate panel location after showing the JFrame in order to get the right insets (window's title bar).
    int panelX = (getWidth() - panel.getWidth() - getInsets().left - getInsets().right) / 2;
    int panelY = ((getHeight() - panel.getHeight() - getInsets().top - getInsets().bottom) / 2);
    panel.setLocation(panelX, panelY);
}

public static void main(String[] args) {
    new a();
}
}
David Oliván
  • 2,717
  • 1
  • 19
  • 26
  • `getContentPane().setLayout(null);` This Q&A was cited in another question at SO. For the record, a `null` layout is not the way to go here. It is rarely, if **ever** the right way to go. – Andrew Thompson May 17 '13 at 09:17