在JFrame中将JPanel居中 [英] Center a JPanel in a JFrame
本文介绍了在JFrame中将JPanel居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不使用布局管理器的情况下将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)
),则需要计算JPanel
在JFrame
内的位置,例如:
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();
}
}
这篇关于在JFrame中将JPanel居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文