A Centered Frame
Home ] Up ] Your First Frame ] Sizing a Frame ] Positioning a Frame ] Exiting a Program ] [ A Centered Frame ]

 

 

Let's create a window with a specific computed size, centered within the screen, and with a different icon in the title bar:

package swingExamples;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JFrame;

class CenteredFrame extends JFrame
{
  public CenteredFrame()
  {
    setTitle("Centered Frame");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension dim = tk.getScreenSize();
    int screenHeight = dim.height;
    int screenWidth  = dim.width;
    setSize(screenWidth/2, screenHeight/2);
    setLocation(screenWidth/4, screenHeight/4);
    Image image = tk.getImage("icon.gif");
    setIconImage(image);
  }
  
  public static void main(String[] args)
  {
    CenteredFrame frame = new CenteredFrame();
    frame.setVisible(true);
  }
}

Which produces the following fascinating output.  The frame will be centered horizontally and vertically on the screen.

Clearly, we need to start placing some content into this frame to make it more interesting.  

Onward!

 

This page was last modified on 02 October, 2007