一个新建的JFrame在调用后,它出现在显示屏上的位置是默认的,即X,Y都为零.但是我想让这个界面显示在屏幕正中,我就用了setLocation这个方法自定义X,Y的坐标.虽然这样是实现了界面到屏幕中间,但是在启动的时候屏幕会闪一下,可以看出来界面是现在默认位置然后才到我自定义的地方,这个是什么原因? 就没有办法让他直接出现在我自定义的地方?

解决方案 »

  1.   

    setBounds
    public void setBounds(int x,
                          int y,
                          int width,
                          int height)重绘组件的指定矩形区域。 覆盖:
    类 Component 中的 setBounds
    参数:
    x - 组件的新 x 坐标
    y - 组件的新 y 坐标
    width - 组件的新 width
    height - 组件的新 height
      

  2.   

    setVisible放在构建frame的最后?
      

  3.   

    是的,要先setlocation再 setVisible。  
      

  4.   

    这种情况也适用于启动就使窗口最大化等操作,一般来说setVisible会放在初始化代码的最后一行。
      

  5.   

    窗口居中
    this.setLocationRelativeTo(null);
      

  6.   

    public   static   void   centerWindow(Component   component)   
        {   
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   
            Dimension componentSize = component.getSize(); 
            
            if (componentSize.height > screenSize.height){   
               componentSize.height = screenSize.height;   
            }
            
            if (componentSize.width > screenSize.width){   
               componentSize.width   =   screenSize.width;   
            }
            
            component.setLocation((screenSize.width - componentSize.width)/2,(screenSize.height - componentSize.height)/2);   
            component.setVisible(true);   
        }
      

  7.   

    两个居中
    1、显示器居中public static final void centerWindow(Component comp) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension compSize = comp.getSize();
        if (compSize.height > screenSize.height) {
          compSize.height = screenSize.height;
        }
        if (compSize.width > screenSize.width) {
          compSize.width = screenSize.width;
        }
        comp.setLocation((screenSize.width - compSize.width) / 2, (screenSize.height - compSize.height) / 2);
      }2、相对另一个组件居中public static final void centerWindow(Component parent, Component comp) {
        if (parent == null) {
          centerWindow(comp);
          return;
        }
        Dimension parentSize = parent.getSize();
        int centerX = parent.getLocation().x + parentSize.width / 2;
        int centerY = parent.getLocation().y + parentSize.height / 2;
        Dimension compSize = comp.getSize();
        comp.setLocation(centerX - compSize.width / 2, centerY - compSize.height / 2);
      }