在JFrame中将JPanel居中

人气:1,041 发布:2022-10-16 标签: swing netbeans jpanel jframe

问题描述

如何在不使用布局管理器的情况下将JPanel放置在JFrame的中心?我希望它对于所有屏幕分辨率都是通用的.

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.

谢谢, 墨粉

推荐答案

如果不使用布局(setLayout(null)),则需要计算JPanelJFrame内的位置,例如:

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

606