在JFrame中居中JPanel
答
如果不使用布局(setLayout(null)
),你需要计算JFrame
内JPanel
的位置,如:
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();
}
}
+0
`getContentPane()。setLayout(null);`这个问答在SO的另一个问题中被引用。为了记录,'null'布局不是这里的路。如果**是正确的,那么很少。 – 2013-05-17 09:17:34
我认为它是一个非常简单的程序。但是如果有人会告诉我如何将JPanel放在JFrame中,无论是否有布局管理器,我都会很高兴。谢谢。 – tomericco 2011-02-04 09:35:03