CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Swing

Swing
Frames
Toolkit class

Two methods of the Toolkit class

Method Description
getDefaultToolkit() A static method that returns the Toolkit object for the current system.
getScreenSize() Returns the screen resolution as a Dimension object.

Two fields of the Dimension class

Field Description
height Stores the height of this Dimension object as an int.
width Stores the width of this Dimension object as an int.

How to center a frame using the Toolkit class

  • The number of pixels per screen varies depending on the resolution setting of the user's monitor.
  • To determine the number of pixels for the current screen, you can use a Toolkit object, or toolkit, to return a Dimension object that contains the number of pixels for the current screen.
  • The Toolkit and Dimension classes are in the java.awt package.

A method that centers a frame on the screen

private void centerWindow(Window w)
{
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    setLocation((d.width-w.getWidth())/2,
        (d.height-w.getHeight())/2);
}

The constructor for a class that defines a centered frame

FutureValueFrame()
{
    setTitle("Future Value Calculator");
    setSize(267, 200);
    centerWindow(this);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Previous | Display a frame | Set the default close operation | Toolkit class | Next