swing中怎么让窗口居中显示

2025-03-25 19:28:48
推荐回答(1个)
回答(1):

// 设置子组件到父组件的中央位置
public static void setToCenter(final Component parent, final Component child) {
   if (child == null) return;
   Dimension pd = Toolkit.getDefaultToolkit().getScreenSize(), screen = pd;
   Point pp = new Point(0, 0);
   if (parent != null) {
      pp = parent.getLocation();
      pd = parent.getSize();
   }
   Dimension cd = child.getSize();
   pp.x = pp.x + (pd.width - cd.width) / 2;
   pp.y = pp.y + (pd.height - cd.height) / 2;
   if (pp.x < 0 || pp.x >= screen.width) {
      pp.x = 0;
   }
   if (pp.y < 0 || pp.y >= screen.height) {
      pp.y = 0;
   }
   child.setLocation(pp);
}