Center a JPanel in a JFrame

你说的曾经没有我的故事 提交于 2019-12-11 12:42:58

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/4855605/center-a-jpanel-in-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!