Main Page

Previous Next

Basics of Components

There's quite a lot of basic stuff that is common to all components that we have to examine before we can apply components properly. It also has applications in many different contexts. While this may seem like something of a catalog of classes and methods, without much in the way of practical application, please stay with it. We will be using most of these capabilities in a practical context later. To understand the fundamental things we can do with Swing components, we will examine what functionality they inherit from the Component and Container classes.

When a component is contained within another component, the outer object is referred to as the parent. You can find out what the parent of any given component is by calling its getParent() method. This method is inherited from the Component class and it returns the parent as type Container, since only a subclass of Container can hold other components. If there is no parent, as is the case with a JFrame component, this method will return null.

Component Attributes

The Component class defines attributes, which record the following information about an object:

  • The position is stored as (x, y) coordinates. This fixes where the object is in relation to its container in the coordinate system of the container object.

  • The name of the component is stored as a String object.

  • The size is recorded as values for the width and the height of the object.

  • The foreground color and background color that apply to the object. These color values are used when the object is displayed.

  • The font used by the object when text is displayed.

  • The cursor for the object – this defines the appearance of the cursor when it is over the object.

  • Whether the object is enabled or not – when a component is enabled its enabled state is true and it has a normal appearance. When a component is disabled it is grayed out. Note that a disabled component can still originate events.

  • Whether the object is visible on the screen or not – if an object is not marked as visible it is not drawn on the screen.

  • Whether the object is valid or not – if an object is not valid, layout of the entities that make up the object has not been determined. This is the case before an object is made visible. You can make a Container object invalid by changing its contents. It will then need to be validated before it is displayed correctly.

You can only modify the characteristics of a Component object by calling its methods or affecting it indirectly in some way since none of the data members that store its characteristics are directly accessible – they are all private. For example, you can change the name of a Component object myWindow with the statement:

myWindow.setName("The Name");

If you subsequently want to retrieve the name of an object, you can use the getName() method which returns the name as a String object. For example:

String theName = myWindow.getName();

The isVisible(), isEnabled(), and isValid()methods return true if the object is visible, enabled, and valid respectively. You can set an object as visible or enabled by passing a value true as an argument to the methods setVisible() and setEnabled() respectively.

A common misconception with Swing components is that calling setEnabled(false) will inhibit events such as mouse clicks from the component. This is not the case. All it does is to set the internal enabled status to false and cause the component to be grayed out. To prevent events from a disabled component having an effect, you must call isEnabled() for the component in your event handling code to determine whether the component is enabled or not. You can then choose to do nothing when the isEnabled() method returns false.

Let's see how we can change the size and position of a Component object.

The Size and Position of a Component

Position is defined by x and y coordinates of type int, or by an object of type Point. A Point object has two public data members, x and y, corresponding to the x and y coordinate values. Size is defined by width and height, also values of type int, or by an object of type Dimension. The class Dimension has two public members of type int, namely width and height. The size and position of a component are often specified together by an object of type Rectangle. A Rectangle object has public data members, x and y, defining the top-left corner of the rectangle, with width and height members defining its size. All these data members are of type int.

Components have a 'preferred' size, which depends on the particular object. For example, the preferred size of a JButton object that defines a button is the size that accommodates the label for the button. Note that you will not normally adjust the size of a component unless you are placing it relative to your display screen, since the size will be managed automatically when it has a parent component. We will see the reason for this later in this chapter. A component also has a minimum size and if the space available to it is less than the minimum size, the component will not be displayed.

The methods to retrieve or alter the size and position are:



void setBounds(int x, int y, int width, int height)

Sets the position of the Component object to the coordinates (x, y), and the width and height of the object to the values defined by the third and fourth arguments.

void setBounds(Rectangle rect)

Sets the position and size of the Component object to be that of the Rectangle argument, rect.

Rectangle getBounds()

Returns the position and size of the object as an object of type Rectangle.

void setSize(Dimension d)

Sets the width and height of the Component object to the values stored in the members of the object d.

Dimension getSize()

Returns the current size of the Component object as a Dimension object.

setLocation(int x, int y)

Sets the position of the component to the point defined by (x, y).

setLocation(Point p)

Sets the position of the component to the point p.

Point getLocation()

Returns the position of the Component object as an object of type Point.

Another important method defined in the Component class is getToolkit(). This returns an object of type Toolkit that contains information about the environment in which your application is running, including the screen size in pixels. You can use the getToolkit() method to help set the size and position of a window on the screen. We can modify the previous example to demonstrate this.

Try It Out – Sizing Windows with Toolkit

We'll use the Toolkit object to display the window in the center of the screen with the width and height set as half of the screen width and height:

import javax.swing.JFrame;
import java.awt.Toolkit;
import java.awt.Dimension;

public class TryWindow {
  // The window object
  static JFrame aWindow = new JFrame("This is the Window Title"); 

  public static void main(String[] args) {
    Toolkit theKit = aWindow.getToolkit();       // Get the window toolkit
    Dimension wndSize = theKit.getScreenSize();  // Get screen size

    // Set the position to screen center & size to half screen size
    aWindow.setBounds(wndSize.width/4, wndSize.height/4,   // Position
                      wndSize.width/2, wndSize.height/2);  // Size
    aWindow.setVisible(true);                    // Display the window

If you try this example, you should see the application window centered on your display with a width and height of half that of the screen.

How It Works

The Toolkit object, theKit, is obtained by calling the getToolkit() method for the JFrame object, aWindow. This object represents the environment on your computer so it encapsulates all the properties and capabilities of that environment as far as Java is concerned, including the screen resolution and size.


Note that you can't create a Toolkit object directly since Toolkit is an abstract class. There is only one Toolkit object in an application – the one that you get a reference for when you call getToolKit() for a component.

The getScreenSize() method that is a member of the Toolkit object returns an object of type Dimension containing data members width and height. These hold the number of pixels for the width and height of your display. We use these values to set the coordinates for the position of the window, and the width and height of the window through the setBounds() method.

This is not the only way of centering a window. A java.awt.GraphicsEnvironment object contains information about the graphics devices attached to a system, including the display – or displays-in systems with more than one. You can obtain a reference to a GraphicsEnvironment object that encapsulates information about the graphics devices on the local machine by calling the static getLocalGraphicsEnvironment() method, like this:

GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();

You can now call this object's getCenterPoint() method to obtain a Point object containing the coordinates of the center of the screen:

Point center = localGE.getCenterPoint();

We could try this with a variation on the original version of TryWindow.

Try It Out – Centering a Window

Here's the code:

import javax.swing.JFrame;
import java.awt.Point;
import java.awt.GraphicsEnvironment;

public class TryWindow 
  // The window object
  static JFrame aWindow = new JFrame("This is the Window Title"); 

  public static void main(String[] args) {
    Point center = 
    int windowWidth = 400;
    int windowHeight = 150;
    // set position and size
    aWindow.setBounds(center.x-windowWidth/2, center.y-windowHeight/2,
                      windowWidth, windowHeight); 
    aWindow.setVisible(true);                    // Display the window

When you execute this you should see the window displayed centered on your screen.

How It Works

This uses the coordinates of the point returned by the getCenterPoint() method to position the window. We calculate the position of the top-left corner of the application window by subtracting half the window width and half the height from the x and y coordinates of the screen center point, respectively.

Points and Rectangles

Let's digress briefly into more detail concerning the Point and Rectangle classes before continuing with the Component class methods, as they are going to come up quite often. Both these classes are defined in java.awt. You will find many of the methods provided by the Point and Rectangle classes very useful when drawing in a window. Entities displayed in a window will typically have Rectangle objects associated with them that define the areas within the window that they occupy. Point objects are used in the definition of other geometric entities such as lines and circles, and to specify their position in a window.

Note that neither Point nor Rectangle objects have any built-in representation on the screen. They aren't components; they are abstract geometric entities. If you want to display a rectangle you have to draw it. We will see how to do this in Chapter 13.

Point Objects

As we said, the Point class defines a point by two public data members of type int, x and y. Let's look at the methods that the class provides.

Try It Out – Playing with Point Objects

Try the following code:

import java.awt.Point;

public class PlayingPoints 
  public static void main(String[] args) {
    Point aPoint = new Point();             // Initialize to 0,0
    Point bPoint = new Point(50,25);
    Point cPoint = new Point(bPoint);
    System.out.println("aPoint is located at: " + aPoint);
    aPoint.move(100,50);                    // Change to position 100,50

    bPoint.x = 110;
    bPoint.y = 70;

    aPoint.translate(10,20);                // Move by 10 in x and 20 in y
    System.out.println("aPoint is now at: " + aPoint);

      System.out.println("aPoint and bPoint are at the same location.");

If you run the program you should see:

aPoint is located at: java.awt.Point[x=0,y=0]
aPoint is now at: java.awt.Point[x=110,y=70]
aPoint and bPoint are at the same location.

How It Works

You can see the three constructors that the Point class provides in action in the first few lines. We then manipulate the Point objects we've instantiated.

You can change a Point object to a new position with the move() method. Alternatively, you can use the setLocation() method to set the values of the x and y members. The setLocation() method does exactly the same as the move() method. It is included in the Point class for compatibility with the setLocation() method for a component. For the same reason, there is also a getLocation() method in the Point class that returns a copy of the current Point object. As the example shows, you can also translate a Point object by specified distances in the x and y directions using the translate() method.

Lastly, you can compare two Point objects using the equals() method. This compares the x and y coordinates of the two Point objects, and returns true if both are equal. The final output statement is executed because the Point objects are equal.

Note that this is not the only class that represents points. We will see other classes that define points when we discuss how to draw in a window.

Rectangle Objects

As discussed earlier, the Rectangle class defines four public data members, all of type int. The position of a Rectangle object is defined by the members x and y, and its size is defined by the members width and height. As they are all public class members, you can retrieve or modify any of these directly, but your code will be a little more readable if you use the methods provided.

There are no less than seven constructors that you can use:




Creates a rectangle at (0, 0) with zero width and height.

Rectangle(int x, int y, int width, int height)

Creates a rectangle at (x, y) with the specified width and height.

Rectangle(int width, int height)

Creates a rectangle at (0, 0) with the specified width and height.

Rectangle(Point p, Dimension d)

Creates a rectangle at point p with the width and height specified by d.

Rectangle(Point p)

Creates a rectangle at point p with zero width and height.

Rectangle(Dimension d)

Creates a rectangle at (0, 0) with the width and height specified by d.

Rectangle(Rectangle r)

Creates a rectangle with the same position and dimensions as r.

You can retrieve or modify the position of a Rectangle object using the method getLocation() that returns a Point object, and setLocation() that comes in two versions, one of which requires x and y coordinates of the new position as arguments and the other, which requires a Point object. You can also apply the translate() method to a Rectangle object, in the same way as the Point object.

To retrieve or modify the size of a Rectangle object you use the methods getSize(), which returns a Dimension object, and setSize(), which requires either a Dimension object specifying the new size as an argument, or two arguments corresponding to the new width and height values as type int.

There are also several methods that you can use to combine Rectangle objects, and also to extend a Rectangle object to enclose a point. The effects of each of these methods are shown in the following diagram.

Click To expand

The rectangle that results from each operation is shown dashed. The methods illustrated in the diagram are:



Rectangle intersection(Rectangle r)

Returns a Rectangle object that is the intersection of the current object and the argument. If the two rectangles do not intersect, the Rectangle object returned is at position (0, 0) and the width and height members are zero so the rectangle is empty.

Rectangle union(Rectangle r)

Returns the smallest Rectangle object enclosing both the current Rectangle object and the Rectangle object r, passed as an argument.

void add(Rectangle r)

Expands the current Rectangle object to enclose the argument Rectangle.

void add(Point p)

Expands the current Rectangle object to enclose the Point object p. The result will be the smallest rectangle that encloses the original rectangle and the point.

void add(int x, int y)

Expands the current Rectangle object to enclose the point at (xy).

void grow(int h, int v)

Enlarges the current Rectangle object by moving the boundary out from the center by h horizontally and v vertically.

You can also test and compare Rectangle objects in various ways with the following methods:



boolean isEmpty()

Returns true if the width and height members of the current Rectangle object are zero, and false otherwise.

boolean equals(Object rect)

Returns true if the Rectangle object passed as an argument is equal to the current Rectangle object, and returns false otherwise.

The two rectangles will be equal if they are at the same position and have the same width and height. If the argument is not a Rectangle object, false is returned.

boolean intersects(Rectangle rect)

Returns true if the current Rectangle object intersects the Rectangle object passed as an argument, and false otherwise.

boolean contains(Point p)

Returns true if the current Rectangle object encloses the Point argument p, and false otherwise.

boolean contains(int x, int y)

Returns true if the current Rectangle object encloses the point (x, y), and false otherwise.

All of these will be useful when dealing with the contents of a Java window. You will then be dealing with points and rectangles describing the contents drawn in the window. For example, you might want to enable the user of your program to select some geometric shape from among those displayed on the screen, in order to work with it. You could use the contains() method to check whether the point corresponding to the current cursor position is within any of the Rectangle objects that enclose each of the circles, lines, or whatever is displayed in the window. Then you can decide which of the objects displayed on the screen the user wants to choose.

There are other classes defining rectangles that we shall meet when we start drawing in a window.

Visual Characteristics of a Component

Two things determine the visual appearance of a component: the representation of the component created by the Java code in the component class that is executed when the component is displayed, and whatever you draw on the component. You can draw on a Component object by implementing its paint() method. We used this method in Chapter 1 to output the text for our applet. The paint() method is called automatically when the component needs to be drawn.

The need to draw a component can arise quite often for a variety of reasons – for example, your program may request that the area that the component occupies should be redrawn, or the user may resize the window containing the component. Your implementation of this method must include code to generate whatever you want drawn within the Component object. Note that the component itself – the JButton or JFrame or whatever, will be drawn for you. You only need to override the paint() method for anything additional that you want to draw on it. We will be overriding the paint() method in Chapter 17 to draw in a window, so we will leave further discussion of it until then.

You can alter some aspects of the appearance of the basic component by calling methods for the object. The following methods have an effect on the appearance of a Component object:



void setBackground(Color aColor)

Sets the background color to aColor. The background color is the color used for the basic component, as created by the operating system.

Color getBackground()

Retrieves the current background color.

void setForeground(Color bColor)

Sets the foreground color to bColor. The foreground color is the color used for anything appearing on the basic component, such as the label on a button, for example.

Color getForeground()

Retrieves the current foreground color.

void setCursor(Cursor aCursor)

Sets the cursor for the component to aCursor. This sets the appearance of the cursor within the area occupied by the Component object.

void setFont(Font aFont)

Sets the font for the Component object.

Font getFont()

Returns the Font object used by the component.

To be able to make use of these properly, we need to understand what Color objects are, and we also need to know how to create Cursor and Font objects.

Defining Color

A screen color is represented by an object of class Color. You define a color value as a combination of the three primary colors: red, green, and blue. They are usually expressed in that sequence, and are often referred to as RGB values. There are other ways of specifying colors in Java, but we will confine ourselves to RGB. You can specify the intensity of each primary color to be a value between 0 and 255. If the intensities of all three are 0, you have the color black, and if all three are set to 255 you have white. If only one intensity value is positive and the others are zero, you will have a pure primary color; for example (0, 200, 0) will be a shade of green. We could define variables corresponding to these colors with the statements:

Color myBlack = new Color(0,0,0);           // Color black
Color myWhite = new Color(255,255,255);     // Color white
Color myGreen = new Color(0,200,0);         // A shade of green

The three arguments to the constructor correspond to the intensities of the red, green, and blue components of the color respectively. The Color class defines a number of standard color constants as public final static variables, whose RGB values are given in parentheses:


(255, 255, 255)


(255, 0, 0)


(255, 175, 175)


(192, 192, 192)


(255, 200, 0)


(255, 0, 255)


(128, 128, 128)


(255, 255, 0)


(0, 255, 255)


(64, 64, 64)


(0, 255, 0)


(0, 0, 255)


(0, 0, 0,)


So if we want our window in the previous example to have a pink background, we could add the statement:


When you have created a Color object, you can brighten or darken the color it represents by calling its brighter() or darker() methods, which will increase or decrease the intensity of the color components by a predefined factor:

thisColor.brighter();                       // Brighten the color
thatColor.darker();                         // Darken the color

The intensities of the component colors will always remain between 0 and 255. When you call brighter and a color component is already at 255, it will remain at that value. The other component intensities will be increased if they are less than 255. In a similar way, the darker() method will not change a component intensity if it is zero. The factor used for darkening a color component is 0.7. To brighten a color component the intensity is increased by 1/0.7.

A fundamental point to remember here is that you can only obtain the colors available within the computer and the operating system environment on which your Java program is running. If you only have a limited range of colors, the brighter() and darker() methods may appear to have no effect. Although you can create Color objects that are supposed to represent all kinds of colors, if your computer only suppgorts sixteen colors you will always end up with one of your sixteen. If your machine supports 24-bit color and this is supported in your system environment, then everything should be fine and dandy.

You can obtain any of the component intensities by calling getRed(), getGreen(), or etBlue() for a Color object. A color can also be obtained as a value of type int that is a composite of the red, green, and blue components of the color represented by a Color object using the getRGB() method. You can also create a Color object from a single RGB value of type int.

To compare two Color objects you can use the equals() method. For example to compare two color objects colorA and colorB, you could write:

  // Do something...

The equals()method will return true if all three components of the two Color objects are equal. You could also use the getRGB() method to do the same thing:

if(colorA.getRGB() == colorB.getRGB())
  // Do something....

This compares the two integer RGB values for equality.

System Colors

The package java.awt defines the class SystemColor as a subclass of the Color class. The SystemColor class encapsulates the standard system colors used for displaying various components. The class contains definitions for 24 public final static variables of type SystemColor that specify the standard system colors used by the operating system for a range of GUI components. For example, the system colors for a window are referenced by:


Defines the background color for a window.


Defines the text color for a window.


Defines the border color for a window.

You can find the others covering colors used for menus, captions, controls, and so on, if you need them, by looking at the documentation for the SystemColor class.

If you want to compare a SystemColor value with a Color object you have created, then you must use the getRGB() method in the comparison. This is because the SystemColor class stores the colors internally in a way that makes use of the fields it inherits from the Color class differently from a normal Color object. For example, to see whether colorA corresponds to the system background color for a window you would write:

if(colorA.getRGB() == SystemColor.WINDOW.getRGB())
  // colorA is the window background color...

Creating Cursors

An object of the Cursor class represents a mouse cursor. The Cursor class contains a range of final static constants that specify standard cursor types. You use these to select or create a particular cursor. The standard cursor types are:
















The resize cursors are the ones you see when resizing a window by dragging its boundaries. Note that these are not like the Color constants, which are Color objects – these constants are of type int, not type Cursor, and are intended to be used as arguments to a constructor.

To create a Cursor object representing a text cursor you could write:

Cursor myCursor = new Cursor(Cursor.TEXT_CURSOR);

Alternatively you can retrieve a cursor of the predefined type using a static class method:

Cursor myCursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR);

This method is particularly useful when you don't want to store the Cursor object, but just want to pass it to a method, such as setCursor() for a Component object.

If you want to see what the standard cursors look like, you could add a cursor to the previous example, along with the pink background:

Try It Out – Color and Cursors

We will change the background color of the content pane for the application window and try out a different cursor. Make the following changes to; we will use the code we created earlier that utilizes the toolkit:

import javax.swing.JFrame;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Cursor;

public class TryWindow
  // The window object
  static JFrame aWindow = new JFrame("This is the Window Title"); 

  public static void main(String[] args)
    Toolkit theKit = aWindow.getToolkit();       // Get the window toolkit
    Dimension wndSize = theKit.getScreenSize();  // Get screen size

    // Set the position to screen center & size to half screen size
    aWindow.setBounds(wndSize.width/4, wndSize.height/4,   // Position
                      wndSize.width/2, wndSize.height/2);  // Size
    aWindow.setVisible(true);                              // Display the window

You can try all the cursors by plugging in each of the standard cursor names in turn. You could also try out a few variations on the background color.

Selecting Fonts

An object of type Font represents a font. The Font class is actually quite complicated, so we'll only scratch the surface enough for our needs here. The Font class differentiates between a character, the letter uppercase 'Q' say, and a glyph, which is the shape defining its appearance when it is displayed or printed. In general a given character in one font will have a different glyph in a different font. For fonts corresponding to many languages, German, French, or Finnish for example, a character may involve more than one glyph to display it. This is typically the case for characters that involve diacritic marks, which are additional graphics attached to a character. The letter ä for instance combines the normal letter 'a' with an umlaut, the two dots over it, so it may be represented by two glyphs, one for the appearance of the letter and the other for the appearance of the umlaut. A Font object contains a table that maps the Unicode value for each character to the glyph code or codes that create the visual representation of the character.

To create a Font object you must supply the font name, the style of the font, and the point size. For example, consider the following statement:

Font myFont = new Font("Serif", Font.ITALIC, 12);

This defines a 12-point Times Roman italic font. The other options you could use for the style are PLAIN and BOLD. The name we have given to the font here, "Serif", is a logical font name. Other logical font names we could have used are "Dialog", "DialogInput", "Monospaced", "SansSerif" or "Symbol". Instead of a logical font name, we can supply a font face name – the name of a particular font such as "Times New Roman" or "Palatino".

It is important to keep in mind that fonts are for presenting characters visually, on the screen or on a printer for instance. Although Java has a built-in capability to represent characters by Unicode codes, it doesn't have any fonts because it doesn't display or print characters itself. The responsibility for this rests entirely with your operating system. Although your Java programs can store strings of Japanese or Tibetan characters, if your operating system doesn't have fonts for these characters you can't display or print them. Therefore to display or print text in the way that you want, you need to know what font face names are available in the system on which your code is running. We will come back to this in a moment.

You can specify combined styles by adding them together. If we want myFont to be BOLD and ITALIC we would have written the statement as:

Font myFont = new Font("Serif", Font.ITALIC + Font.BOLD, 12);

You retrieve the style and size of an existing Font object by calling its methods getStyle() and getSize(), both of which return a value of type int. You can also check the individual font style for a Font object with the methods isPlain(), isBold(), and isItalic(). Each of these methods returns a boolean value indicating whether the Font object has that style.

Before you create a font using a particular font face name, you need to know that the font is available on the system where your code is executing. For this you need to use a method, getAllFonts(), in the GraphicsEnvironment class defined in the java.awt package. We met this class earlier when we were centering a window. We could do this as follows:

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();     // Get the fonts

We get a reference to the GraphicsEnvironment object for the current machine by calling the static method getLocalGraphicsEnvironment() as illustrated. We then use this to call its getAllFonts() method. The getAllFonts() method returns an array of Font objects consisting of those available on the current system. You can then check this list for the font you want to use. Each of the Font instances in the array will be of a 1 point size, and since 1 point is approximately 1/72 of an inch or 0.353mm, you will typically want to change this unless your screen and eyesight are really exceptional. To change the size and/or style of a font you call its deriveFont() method. This method comes in three versions, all of which return a new Font object with the specified size and/or style:

deriveFont() Method


deriveFont(int Style)

Creates a new Font object with the style specified – one of PLAIN, BOLD, ITALIC or BOLD+ITALIC.

deriveFont(float size)

Creates a new Font object with the size specified.

deriveFont(int Style, float size)

Creates a new Font object with the style and size specified.

To use the last font from the array of Font objects to create an equivalent 12-point font you could write:

Font newFont = fonts[fonts.length-1].deriveFont(12.0f);

If you look in the documentation for the Font class, you will see that there is a fourth version of deriveFont() that involves an AffineTransform, but we'll leave AffineTransform objects until Chapter 18.

Getting a Font object for every font in the system can be a time-consuming process if you have many fonts installed. A much faster alternative is to get the font names, and then use one of these to create the Font object that you require. You can get the face names for all the fonts in a system like this:

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();

The array fontnames will contain the names of all the font faces available, and you can use one or more of these to create the Font objects you need.

Try It Out – Getting the List of Fonts

This program will output your screen size and resolution, as well as the list of font family names installed on your machine:

import java.awt.*;

public class SysInfo 
  public static void main(String[] args) {
    Toolkit theKit = Toolkit.getDefaultToolkit();

    System.out.println("\nScreen Resolution: " 
                      + theKit.getScreenResolution() + " dots per inch");

    Dimension screenDim = theKit.getScreenSize();
    System.out.println("Screen Size: " 
                      + screenDim.width + " by " 
                      + screenDim.height + " pixels");

    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontnames = e.getAvailableFontFamilyNames();
    System.out.println("\nFonts available on this platform: ");
    for (int i = 0; i < fontnames.length; i++)


On my system I get the following output:

Screen Resolution: 120 dots per inch

Screen Size: 1280 by 1024 pixels

Fonts available on this platform:

Abadi MT Condensed Light


Albertus Extra Bold

Albertus Medium



Allegro BT

AmerType Md BT



Antique Olive

Antique Olive Compact



Arial Alternative

Arial Alternative Symbol

Arial Black

Arial MT Black many more.

How It Works

We first get a Toolkit object by calling the static method getDefaultToolkit() – this is the key to the other information. The getScreenResolution()returns the number of pixels per inch as a value of type int. The getScreenSize() method returns a Dimension object which specifies the width and height of the screen in pixels.

We use the getAllFonts() method discussed previously to get a String array containing the names of the fonts which we output to the screen.

Font Metrics

Every component has a method getFontMetrics() that you can use to retrieve font metrics – the wealth of dimensional data about a font. You pass a Font object as an argument to the method, and it returns an object of type FontMetrics that you can use to obtain data relating to the particular font. For example, if aWindow is a Frame object and myFont is a Font object, you could obtain a FontMetrics object corresponding to the font with the statement:

FontMetrics metrics = aWindow.getFontMetrics(myFont);

You could use the getFont() method for a component to explore the characteristics of the font that the component contains. For example:

FontMetrics metrics = aWindow.getFontMetrics(aWindow.getFont());

You can now call any of the following FontMetrics methods for the object to get at the basic dimensions of the font:



int getAscent()

Returns the ascent of the font, which is the distance from the base line to the top of the majority of the characters in the font. The base line is the line on which the characters rest. Depending on the font, some characters can extend beyond the ascent.

int getMaxAscent()

Returns the maximum ascent for the font. No character will exceed this ascent.

int getDescent()

Returns the descent of the font, which is the distance from the base line to the bottom of most of the font characters that extend below the base line. Depending on the font, some characters may extend beyond the descent for the font.

int getMaxDescent()

Returns the maximum descent of the characters in the font. No character will exceed this descent.

int getLeading()

Returns the leading for the font, which is the line spacing for the font – that is the spacing between the bottom of one line of text and the top of the next. The term originated when type was actually made of lead, and there was a strip of lead between one line of type and the next when a page was typeset.

int getHeight()

Returns the height of the font, which is defined as the sum of the ascent, the descent, and the leading.

Click To expand

The diagram shows how the dimensions relate to the font. The advance width for a character is the distance from the reference point of the character to the reference point of the next character. The reference point for a character is on the base line at the left edge of the character. Each character will have its own advance width which you can obtain by calling a FontMetrics method charWidth(). For example, to obtain the advance width for the character 'X' the following statement could be used:

int widthX = metrics.charWidth('X');

You can also obtain the advance widths for all the characters in the font as an array of type int with the method getWidths():

int[] widths = metrics.getWidths();

The numerical value for the character is used to index the array, so you can get the advance width for the character 'X' with the expression widths['X']. If you just want the maximum advance width for the characters in the font, you can call the method getMaxAdvance(). Lastly, you can get the total advance width for a String object by passing the object to the method stringWidth(). The advance width is returned as a value of type int.

Although you now know a great deal about how to create and manipulate fonts, we haven't actually created and used one. We will remedy this after we have got a feel for what Swing components can do and learned a little about using containers.

Swing Components

Swing components all have the JComponent class as a base which itself extends the Component class to add the following capability:

  • Supports pluggable look-and-feel for components, allowing you to change the look and feel programmatically, or implement your own look-and-feel for all components displayed.

  • Support for tooltips – a tooltip being a message describing the purpose of a component when the mouse cursor lingers over it. Tooltips are defined by the JTooltip class.

  • Support for automatic scrolling in a list, a table, or a tree when a component is dragged with the mouse.

  • Special debugging support for graphics, providing component rendering in slow motion so you can see what is happening.

  • Component classes can be easily extended to create your own custom components.

All the Swing component classes are defined in the javax.swing package and have class names that begin with J. There are quite a few Swing components, so we'll get an overview of what's available and how the classes relate to one another and then go into the detail of particular components when we use them in examples.


The Swing button classes define various kinds of buttons operated by clicking with a mouse. The button classes have AbstractButton as a base, as shown below.

The JButton class defines a regular pushbutton that you would use as a dialog button or in a toolbar.

This is an example of a JButton object. This component has a border of type BevelBorder added to it.

The JToolBar class is used in conjunction with the JButton class to create a toolbar containing buttons. A toolbar is dockable without any additional programming effort on your part, as we will see.

JToggleButton defines a two-state button, pressed or not, and there are two more specialized versions defined by JCheckBox and JRadioButton. Radio buttons defined as JRadioButton objects generally operate in a group so that only one button can be in the pressed state at any one time. This grouping is established by adding the JRadioButton object to a ButtonGroup object that takes care of the state of the buttons in the group.

This is an example of a JCheckBox object. Clicking on the checkbox changes its state from checked to unchecked or vice versa.

All the buttons can be displayed with a text label, an icon, or both.


The Swing components include support for pop-up or context menus as well as menu bars. The classes defining elements of a menu are shown overleaf.

Click To expand

The JMenuBar class defines a menu bar usually found at the top of an application window. A JMenu object represents a top-level menu item on a menu bar that pops up a list of menu items when it is clicked. The items in a menu are defined by the JMenuItem class. The JPopupMenu class defines a context menu that is typically implemented to appear at the current cursor position when the right mouse button is clicked. A JCheckBoxMenuItem component is a menu item with a checkbox that is ticked when the item is selected. The JRadioButtonMenuItem class defines a menu item that is part of a group where only one item can be selected at any time. The group is created by adding JRadioButtonMenuItem objects to a ButtonGroup object. We will be implementing a menu in an application and an applet later in this chapter.

Text Components

The capability of the Swing text components is very wide indeed.

Click To expand

The most elementary text component is a JLabel object:

A JLabel component is passive and does not react to input events so you can't edit it.

A JTextField component looks similar to a label in that it displays a single line of text, but in this case it is editable.

JFormattedTextField component is a JTextField component that can control and format the data that is displayed or entered. It can supply automatic formatting in many instances. Here it has automatically displayed a Date object as a date.

The JTextArea defines a component that allows editing of multi-line text.

This is an example of a JTextArea component. The scrollbars are supplied automatically and you can also display multiple rows and columns.

The JEditPane and JTextPane components are a different order of complexity from the others and enable you to implement sophisticated editing facilities relatively easily. The JEditPane supports editing of plain text, text in HTML, and RTF (Rich Text Format). The JTextPane class extends JEditPane and allows you to embed images or other components within the text managed by the component.

Other Swing Components

Other Swing components you will use regularly include the JPanel component. The JPanel class defines something like a physical panel that you can use to group a set of components. For instance, you might use two JPanel objects to support two separate groups of JButton components in the content pane of an application window.

The JList and JTable components are also very useful.

This is a JList component that implements a list of items. This component has a border of type EtchedBorder added to it. You can select entries from the list.

This is a JTable component that implements a table of items from which you can select a row, or a column, or a single element. A JTable component automatically takes care of reordering the columns when a column is dragged to a new position using the mouse.

Any component can have a border added, and the javax.swing.borders package contains eight classes representing different kinds of borders you can use for a component.

We have not introduced all the Swing component classes by any means, and you will be meeting a few more as you progress through the rest of the book.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor