2011-01-31 75 views
1

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

感谢, 托梅尔

+0

我认为它是一个非常简单的程序。但是如果有人会告诉我如何将JPanel放在JFrame中,无论是否有布局管理器,我都会很高兴。谢谢。 – tomericco 2011-02-04 09:35:03

回答

-2

如果不使用布局(setLayout(null)),你需要计算JFrameJPanel的位置,如:

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