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
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
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();
}
}