Abstract Windowing Toolkit

Swing sits on top of the awt(abstract wiudowiug toolkit) package.

You must import java.awt.* if you wish to use the awt classes in an applet.

Some Classes in the AWT Package

Some of the classes that the awt package contains are:

Colour

Use the Color class to manipulate a component's or a graphic context's colour information.

The colour c1ass provides class variables for common colours such as red and yellow. We can create our own RGB colours.

Some Color methods are:

Color(int r, int g, int b)        where r, g & b are in the range 0-255
Color(float r, float g, float b)  where r, g & b are in the range 0.0-1.0

Color getColor()
setColor(Color c)

int getRed()
int getGreen()
int getBlue()  

Color example: (Run Applet)

import java.awt.*;
import javax.swing.*;

public class ColourDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        @Override
        public void paintComponent(Graphics g)
        {
            g.drawString("Original colour string", 100, 50);
            Color oldColor = g.getColor();

            g.setColor(Color.blue);
            g.drawString("Blue string", 100, 75);

            int red = 0;
            int green = 255;
            int blue = 0;

            g.setColor(new Color(red, green, blue));
            g.drawString("Green string", 100, 100);

            g.setColor(oldColor);
            g.drawString("Original colour string", 100, 125);
        }
    }
}

Font

Use the Font class to manipulate a component's or a graphic context's font information.

To create an instance of the font class use the Font() constructor method.

For example:

Font(String name, int style, int size) 

The font name can be any font supported by the system where the program is running, such as Monospaced or SansSerif.

The font style can be any combination of the three static constants Font.PLAIN, Font. ITALIC and Font BOLD. To combine two font styles use the + operator.

The font size is measured in points where a point is 1/72 of an inch.

To get a font's name and size use:

String getName()
int getSize()  

To test if a font is plain, bold or italic use:

boolean isPlain()
boolean isBold()
boolean isItalic() 

Use the Graphics class methods getFont() and setFont() to get and set the current font:

Font getFont()
setFont(Font f) 

Font Example: (Run Applet)

import java.awt.*;
import javax.swing.*;

public class FontDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        Font oldFont;
        Font newFont;

        public View()
        {
            super();
            this.newFont = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 24);
        }

        @Override
        public void paintComponent(Graphics g)
        {
            this.oldFont = g.getFont();
            String fontString;
            fontString = "The original font was: " + this.oldFont.getName() + " " + this.oldFont.getSize() + " ";

            if (this.oldFont.isPlain())
            {
                fontString += "plain";
            }
            if (this.oldFont.isBold())
            {
                fontString += "bold ";
            }
            if (this.oldFont.isItalic())
            {
                fontString += "italic ";
            }

            g.drawString(fontString, 10, 50);

            g.setFont(this.newFont);
            g.drawString("Times Roman 24 Bold Italic", 10, 100);

            g.setFont(this.oldFont);
            g.drawString("Original font restored", 10, 150);
        }
    }
}

Paint, Repaint and Update

Whenever we move expose, iconify or deiconify a Panel or Window Java calls the paint() method of all components attached to the Panel or Window.

The repaint() method can be used to repaint a component or part of a component. The repaint() method's syntax is:

repaint()                                    // causes the component's update() method
                                             // to be called as soon as possible.
repaint(int x, int y, int width, int height) // repaint only the selected portion of the component  

The update() method of the Component class:

To move sprites around a component we must override the update() method. We shall discuss this in Section III.

Graphics

The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto Components or onto offscreen Images.

An instance of the Graphics class is also called a graphics context.

Graphics contexts are used to determine all the graphics attributes such as font, line colour and line width.

The argument to the paint() method is an instance of the Graphics class.

To draw a line in the paint() method, use the drawLine() method. Java draws lines using the coordinate system associated with the Container in which the canvas is a component. Java's container coordinate system is the same as a monitor's coordinate system. The origin of a container's coordinate system is the upper left corner of the container's window. The y coordinate increases as we move down the container's window.

A paint mode determines the way in which graphics are drawn. There are two paint modes: overwrite and XOR.          

Use the setOverwriteMode() method to overwrite any other graphics that occupy a pixel that is being set. Overwrite mode is the default mode.

Use the setXORMode() method to overlap any other graphics that occupy a pixel that is being set.

To copy a rectangular area of a component use:

copyArea(int x, int y, int width, int height, int dx, int dy)  

The values dx and dy are the offset from x and y.

Polygons

We can create and then draw Polygons onto the graphics context attached to any Component.

We can declare an instance of a Polygon class using:

Polygon()
Polygon (int xValues[] , int yValues[], int numberOfPoints)  

We can draw the outline of a polygon using:

drawPolygon(int xValues[], int yValues[], int numberOfPoints)
drawPolygon(Polygon p) 

We can fill a polygon using:

fillPolygon(int xValues[], int yValues[], int numberOfPoints)
fillPolygon (Polygon p) 

We can draw a series of connected lines (that do not have to form a closed polygon) using:

drawPolyline(int xValues[], int yValues[], int numberOfPoints) 

To test if a point lies inside a polygon use the contains() method:

boolean contains(int x, int y) 

 

Polygon Fxample: (Run Applet)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PolygonDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements MouseMotionListener
    {
        private final int xValues[] =
        {
            10, 100, 50, 30, 10
        };
        private final int yValues[] =
        {
            10, 10, 50, 100, 100
        };
        private final int numberOfPoints = 5;
        private final Polygon poly = new Polygon(this.xValues, this.yValues, this.numberOfPoints);

        public View()
        {
            super();
            addMouseMotionListener(this);
        }

        @Override
        public void paintComponent(Graphics g)
        {
            g.setColor(Color.red);
            g.fillPolygon(this.poly);
        }

        @Override
        public void mouseDragged(MouseEvent e)
        {
        }

        @Override
        public void mouseMoved(MouseEvent e)
        {
            if (this.poly.contains(e.getX(), e.getY()))
            {
                showStatus("inside");
            }
            else
            {
                showStatus("outside");
            }
        }
    }
}

Rectangles

A Rectangle specifies an area defined by its top-left (x y) coordinate, its width and its height.

Create a rectangle using:     

Rectangle()
Rectangle(Dimension d)
Rectangle(int width, int height)
Rectangle(int x, int y, int width, int height)
Rectangle(Point p)
Rectangle(Point p, Dimension d) 

To draw or fill a rectangle use:

drawRect(int x, int y, int width, int height)
fillRect(int x, int y, int width, int height) // uses the current colour to fill rect  

To draw or fill a rounded rectangle use:

drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) 

Access a rectangle's member variables using:

int height
int width
int x
int y  

Move a rectangle using:

setLocation(int x, int y)
translate(int dx, int dy)  

Resize a rectangle using:

setSize(int width, int height)  

Resize and reposition a rectangle using:

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

Test against a rectangle using:

boolean contains(int x, int y)
boolean intersects(Rectangle r)
Rectangle intersection(Rectangle r)
Rectangle union(Rectangle r)  

Rectangle Example: (Run Applet)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RectangleDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements MouseMotionListener
    {
        private final Rectangle rect = new Rectangle(100, 100, 50, 50);
        private String message = "";
        private int x;
        private int y;

        public View()
        {
            this.addMouseMotionListener(this);
        }

        @Override
        public void mouseMoved(MouseEvent e)
        {
            this.x = e.getX();
            this.y = e.getY();
            if (this.rect.contains(this.x, this.y))
            {
                this.message = "inside";
            }
            else
            {
                this.message = "outside";
            }
            this.repaint();
        }

        @Override
        public void mouseDragged(MouseEvent me)
        {
        }

        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            g.drawString(this.message, this.x, this.y);
        }
    }
}
 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>