Results 1 to 7 of 7

Thread: Center jFrame

  1. #1

    Thread Starter
    Hyperactive Member xxarmoxx's Avatar
    Join Date
    Mar 2007
    Posts
    378

    Center jFrame

    How can I center a jFrame on screen when it loads up? Im using netbeans 6.0.

  2. #2
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: Center jFrame

    i dont think there is a way
    I Use SetLocation method using 2 parameter width & height

  3. #3

    Thread Starter
    Hyperactive Member xxarmoxx's Avatar
    Join Date
    Mar 2007
    Posts
    378

    Re: Center jFrame

    I tried this but it didnt work:

    Code:
    this.setLocation(this.WIDTH,this.HEIGHT);
    Where should I put the code and what do I need to change in order for it to work?

    Thanks for your help

  4. #4
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: Center jFrame

    Code:
    this.setLocation(300,200);

  5. #5

    Thread Starter
    Hyperactive Member xxarmoxx's Avatar
    Join Date
    Mar 2007
    Posts
    378

    Re: Center jFrame

    This works pretty sweet:

    Code:
        public static void centerFrame(JFrame frame) {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point center = ge.getCenterPoint();
            Rectangle bounds = ge.getMaximumWindowBounds();
            int w = Math.max(bounds.width/2, Math.min(frame.getWidth(), bounds.width));
            int h = Math.max(bounds.height/2, Math.min(frame.getHeight(), bounds.height));
            int x = center.x - w/2, y = center.y - h/2;
            frame.setBounds(x, y, w, h);
            if (w == bounds.width && h == bounds.height)
                frame.setExtendedState(Frame.MAXIMIZED_BOTH);
            frame.validate();
        }

  6. #6
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: Center jFrame

    Yes maybe i always use setLocation Not only for the Frame but all other elements because i use JCreator I can only Code !

  7. #7
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Center jFrame

    Try this code, better performance:
    Code:
    Dimension screenResolution = this.getToolkit().getScreenSize();
    this.setLocation((screenResolution.width - this.getWidth()) / 2, (screenResolution.height - this.getHeight()) / 2);
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width