将Jarame中的JPanel居中

时间:2011-01-31 20:14:31

标签: swing netbeans jframe jpanel

如何在不使用布局管理器的情况下将JPanel放在JFrame的中心?我希望它当然适用于所有屏幕分辨率。

谢谢, Tomer的

1 个答案:

答案 0 :(得分:-2)

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

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