The AWT package. Abstract Windowing Toolkit. java.awt.*

Graphics abstractions . Paint . Layout Managers . Components . Drawing images

Let's consider three basic abstractions of the Abstract Windowing Toolkit.

AWT Abstractions

  1. Graphics are defined by colors, fonts, images and other drawing tools
  2. Components are the buttons, lists, checkboxes and other widgets. Some component attributes are defined with graphics (color, ...).
  3. Layout Managers are the objects that are used to control the layout of components.

Classes of the AWT related to the Graphics

Color   Dimension    Font    FontMetrics    Graphics    Image    
Insets  MediaTracker 
Point   Polygon      Rectangle              Toolkit 

Paint

An applet can draw items on the screen with the paint(Graphics) method. Images, lines, circles, polygons or any other graphical items are drawn on a Graphics instance. The browser passes the graphics to the paint(Graphics) method. paint(Graphics) is called several times throughout the life of an applet. If an applet changes location on the screen or any time it needs to be refreshed(redrawn), paint(Graphics) is called. Programmers do not directly call paint(Graphics), to have your applet paint itself call repaint(); repaint() will call update(Graphics) that in its turn calls paint(Graphics). Be aware that update(Graphics) assumes that the background is not cleared and clears background first. If you don't want to waste time to clear the background each time you want to paint, it's a good idea to override update(Graphics) with your own code that only calls for paint.

The next example displays a Java related image and some Java poetry below. All this is placed into a blue filled rectangle drawn inside an applet.

Example

// AppletTwo.java import java.applet.Applet; import java.awt.*; public class AppletTwo extends Applet { private Image image; private String[] javaPoetry = { "I placed my JAR", " in Tennessee", "On a high ", "remote hill...", "Where people can see", " its Java steam", "That shapes ", "their dreams and will..." }; public void init() { image = getImage(getCodeBase(), "jar.gif"); } public void paint(Graphics g) { g.setColor(Color.blue); g.fillRect(10,10, 180, 280); g.drawImage(image, 20, 20, this); g.setColor(Color.white); g.setFont(new Font("Helvetica", Font.BOLD, 14) ); // name, style, size for(int i = 0; i < javaPoetry.length; i++) { g.drawString(javaPoetry[i], 15, 120 + 20*i); } } }

Layout Managers

A layout manager is used to format the location of components within a container. A container (for example the Panel) is a component that can include other components or containers.

Layout of a container can be defined as null. In such a case the size and exact location of each component has to be defined by the programmer. This practice is not recommended because the cross platform portability will be lost.

List of Layout Managers

null, FlowLayout, BorderLayout, GridLayout, GridBagLayout, CardLayout

Most commonly used Layout Managers: FlowLayout, BorderLayout, GridLayout

GridBagLayout

The GridBagLayout is the most flexible layout manager. Any layout created with the other layout managers can be done with the GridBagLayout. This kind of flexibility comes with more complication and more code to write.

Using the GridBagLayout also requires the use of GridBagConstraints. GridBagConstraints has several public constants that are used for positioning components.

How to use GridBagLayout: step by step procedures

  1. Create instance of GridBagLayout
  2. Create instance of GridBagConstraints
  3. Set specific values in constraints object
  4. Set constraints to Component
  5. Add Component to container
  6. Go To 3 for and repeat for each Component being added.
  7. * Only one instance of GridBagConstraints is necessary. Step 4 automatically creates a clone of the constraints.

GridBagLayout Example

The example creates several buttons with the following properties:

/* We can simplify this process by creating a method to * perform steps 4 and 5 of the GridBagLayout Procedures * Set constraints to component and add component to container. **/ protected void setButton(String iName, GridBagLayout iGridBag, GridBagConstraints iConstraints) { Button button = new Button(iName); iGridBag.setConstraints(button, iConstraints); add (button); }

GridBagConstraints Code

The rest of this example performs steps 1,2 and 3 of the GridBagLayout Procedure.

  1. Create instance of GridBagLayout
  2. Create instance of GridBagConstraints
  3. Set specific values in constraints object

The last step is also performed before each call to setButton

6. GoTo 3 and repeat for each Component

GridBagConstraints Code

// GridBagExample public class GridBagExample extends Applet { public void init() { GridBagLayout gridBag = new GridBagLayout(); // step 1 GridBagConstraints gbc = new GridBagConstraints(); // step 2 setLayout(gridBag); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; setButton("Button 1", gridBag, gbc); setButton("Button 2", gridBag, gbc); setButton("Button 3", gridBag, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; setButton("Button 4", gridBag, gbc); gbc.weightx = 0; setButton("Button 5", gridBag, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; setButton("Button 6", gridBag, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; setButton("Button 7", gridBag, gbc); gbc.gridwidth = 1; gbc.gridheight = 2; gbc.weighty = 1.0; setButton("Button 8", gridBag, gbc); gbc.weighty = 0.0; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = 1; setButton("Button 9", gridBag, gbc); setButton("Button 10", gridBag, gbc); } }

Components and Containers

Components and Containers

Containers

Containers hold and organize your Components, but they also contain code for event handling and many 'niceties' such as controlling the cursor image and the application's icon.
Containers:

Component

Components are generally the stuff that the user interacts with. The meat and potatoes of your application. (as discussed in the Introduction).

List of common Components


To view this applet you need a Java-enabled browser

Lets walk through Sun's example written in Java 1.0 style with old event handling and deprecation methods..

public class ComponentTest extends Applet {
    Panel       center;
The following code does
  1. Sets the background to gray
  2. Sets the font to plain 12pt Helvetica font
  3. Sets layout to BorderLayout(i.e "North, South, Center, East, West")
  4. Creates a label "North" that has center alignment
    public void init() {
        setBackground(Color.lightGray);
        setFont(new Font("Helvetica", Font.PLAIN, 12));
        setLayout(new BorderLayout());
        Label l  = new Label("North");
        l.setAlignment(Label.CENTER);
  1. Adds a TextField(i.e Edit control) to the lower porton of the container, which is the applet
  2. Adds the label to the upper portion of the container
  3. Creates a ScrollPanel and sets its layout, then centers it within the container
        add("South", new TextField("South"));
        add("North", l);
        center = new ScrollPanel();
        center.setLayout(new BorderLayout());
        add("Center", center);
  1. Creates another new ScrollPanel (extension of Panel) that is centered within an existing panel(i.e center)
  2. Create a label, Buttons, SillyWidget(see below), a TextField and two scrollbars. All of which are laid out in a "Flow"
        Panel innerPanel = new ScrollPanel();
        center.add("Center", innerPanel);
        innerPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        innerPanel.add(new Label("List of Widgets"));
        innerPanel.add(new Button("Arthur"));
        innerPanel.add(new Button("Sami"));
        innerPanel.add(new SillyWidget());
        innerPanel.add(new TextField("quite random"));
        innerPanel.add(new Scrollbar(Scrollbar.VERTICAL));
        innerPanel.add(new Scrollbar(Scrollbar.HORIZONTAL));
  1. Creation of a new List(i.e Listbox of strings) of 4 items and is not multi-selectable
  2. Resize using the reshape method available to every Component.
  3. Adds strings to the List(i.e "Arthur", "Sami", etc.)
  4. Sets 1(i.e Arthur) to be selected and hilighted
        List li = new List(4, false);  // 4 visible lines, 
													// no multi-line selection
        li.reshape(0, 0, 100, 100);	// move to 0,0 and set size=100x100
        li.addItem("Arthur");
        li.addItem("Sami");
        li.addItem("James");
        li.addItem("Chris");
        li.addItem("Mary");
        li.addItem("Lisa");
        li.addItem("Kathy");
        li.select(1);
  1. Adds the List to the innerPanel which was centered within the first ScrollPanel
  2. Creates a TextArea, of 10 rows by 5 columns
  3. Adds some text and sets the foreground color(i.e text color in this case)
  4. Then adds the TextArea to the panel
        innerPanel.add(li);
        TextArea tx = new TextArea(10, 5);     // 10 cols, 5 rows
        tx.setText("this is some random text");
        tx.setForeground(Color.red);

        innerPanel.add(tx);
  1. Creation of a choice. A choice is similar to a List, but takes a smaller space on the screen as it displays only one selection until the use clicks on it. Note: Once you add something to a choice, you cannot remove it
  2. Adds the choice to the innerPanel
        Choice  opt = new Choice();

        opt.addItem("Arthur");
        opt.addItem("Sami");
        opt.addItem("Chris");
        opt.addItem("Jim");

        innerPanel.add(opt);
  1. Creation of a CheckBoxGroup. A group of checkbox by themselves are independant of each other,
  2. but in a CheckboxGroup only one can be selected at a time.
  3. Creation of Checkboxes that are added to the innerPanel
  4. Creation of two scrollbars.
        CheckboxGroup g = new CheckboxGroup();
        innerPanel.add(new Checkbox("one", g, false));
        innerPanel.add(new Checkbox("two", g, true));  // two=selected
        innerPanel.add(new Checkbox("three", g, false));
        center.add("East", new Scrollbar(Scrollbar.VERTICAL));
        center.add("South", new Scrollbar(Scrollbar.HORIZONTAL));

        add("East", new Button("East"));
        add("West", new Button("West"));
    }
  1. A Synchronized method that handles user input. In this case handleEvent just returns false
  2. because it wants the AWT to handle the events and use the default handling routines
    public synchronized boolean handleEvent(Event e) 
        {
                return false;
        }
    }
Definition of the ScrollPanel used above
class ScrollPanel extends Panel {
    public ScrollPanel() {
        reshape(0, 0, 100, 100);
    }

// Overriden paint method that draws a rectange around the panel
    public void paint(Graphics g) {
        Rectangle r = bounds();

        g.drawRect(0, 0, r.width, r.height);
    }
}

The SillyWidget should look like this:

class SillyWidget extends Canvas {
    Color       c1 = Color.pink;
    Color       c2 = Color.lightGray;
    long        entered = 0;
    long        inComponent = 0;
    Font        font = new Font("Courier", Font.BOLD, 12);
    FontMetrics fm;

    public SillyWidget() {
        reshape(0, 0, 100, 100);
    }

// Called when the mouse enters the Canvas
// This widget is just to change the colors and forcing a repaint 
// when the mouse enters 
    public boolean mouseEnter(Event e, int x, int y) {
        Color c = c1;
        entered = e.when;
        c1 = c2;
        c2 = c;
        repaint();
        return true;
    }

// Called when the mouse exits the Canvas
// This widget is just change the colors and forcing a repaint when the
// mouse exits

    public boolean mouseExit(Event e, int x, int y) {
        Color c = c1;

        inComponent = e.when - entered;
        c1 = c2;
        c2 = c;
        repaint();
        return true;
    }

// Called when the Canvas needs repaint and merely draws a bunch of rectangles
    public void paint(Graphics g) {
        Rectangle       r = bounds();

        g.setColor(c1);
        g.fillRoundRect(0, 0, r.width, r.height, 20, 20);
        g.setColor(c2);
        g.fillRoundRect(5, 5, r.width - 10, r.height - 10, 20, 20);
        g.setColor(c1);
        g.fillRoundRect(15, 15, r.width - 30, r.height - 30, 20, 20);
        g.setColor(Color.darkGray);
        g.setFont(font);
        fm = g.getFontMetrics(font);
        String s = ""+inComponent+" ms.";
        int width = fm.stringWidth(s);
        System.out.println("width = " + width);
        g.drawString(s,
                     (r.width - width) / 2,
                     (r.height - fm.getHeight()) / 2);
    }
}

Back To Java School