<HTML>
<HEAD>

<!-- Change the Title please -->
<TITLE>AWT SHORT COURSE: Overview</TITLE>
</HEAD>

<!-- BODY-TEMPLATE -->

<!-- NAVBAR-PULLQUOTE-TEMPLATE -->
<TR VALIGN=TOP>
<td width=178>

<BR clear=LEFT>
<TABLE ALIGN=LEFT>
<TR VALIGN=TOP>
<td width=60>
<a href="../TOC.html"><img border=0 src="/developer/images/magelang/contents.gif" alt="contents" WIDTH=147 HEIGHT=23></a>
</td>
</tr>
<tr>
<td>
<a href="Overview.html"><img border=0 src="/developer/images/magelang/previous.gif" hspace=10 alt="Previous" width=64 height=20></a>
</td>
<td>
<a href="Widgets.html"><img border=0 src="/developer/images/magelang/next.gif" alt="Next" width=43 height=20></a>
</td>
</tr>
</table>

</TR>
</TABLE>

<!-- PAGETOP-TEMPLATE -->
<TR>
<TD WIDTH=452 ALIGN=RIGHT>
<img src=images/ShortCourse.gif>
</TD>
</TR>
<TR>
<TD WIDTH=452 COLSPAN=2 ALIGN=right>
<!--breadcrumb trail; change to reflect the current URL-->
<!-- Please change to reflect where _exactly_ you are in the site
<!-- Add more subcategories as needed  -->

<!-- Please Change these.  The Links are SubCat#, and titled SubCategory# -->
</TD>
</TR>

<!--- Please put everything you want here to the right of the navbar.
	<TR>
	<TD>
	This is the MAIN TABLE.  Put data HERE unless you need a table that
 	REQUIRES the full screen width, i.e. an event schedule table.
	Add a new table row for the data.

	If the text needs to be in two columns, use this <TR> structure:
	Make the width=452
	<TR>
	<TD WIDTH=226>
	</TD>
	<TD WIDTH=226>
	</TD>
	</TR>

	</TD>
	</TR>
--->

<TR>
<TD width=452>
<p>
<font size=+2>Overview of GUIs in Java</font><P>
</a>


<p>
A GUI consists of a set of components (widgets), such as buttons and text fields, laid out in some form in an applet window.  The components respond to events initiated by physical stimuli, such as mouse clicks, or key presses; by changing the state of the display, or modifying some internal data structure.  For example, here is a <a href="Button.html">Button</a> object that, when pushed, increments an integer in a <a href="TextField.html">TextField</a> object:

<center>
<hr>
<applet code=Counter.class CODEBASE="/applets/magelang/AWT-Training/Examples/" width=100 height=35></applet>
<hr>
</center>

<p>
All the <a href="Widgets.html">widgets</a> that can be added to an applet are subclasses of Component and Java provides a number of them, although you can <a href="http://java.sun.com:80/books/Series/Tutorial/ui/components/canvas.html">define your own</a> by subclassing the Canvas Component.

<p>
How do you make a widget appear in an applet?  The basic formula is:

<ol>
<li>Create the Component with the Java <code>new</code> operator, for example,
<tt><pre>
Button b = new Button("Hit me");
TextField tf = new TextField("0");
</pre></tt>

<li>Add the Component to the applet, for example,
<tt><pre>
add(b);
add(tf);
</pre></tt>

</ol>

<p>
How does adding a Component to an applet cause it to appear? To answer that, it is helpful to understand the notion of a <a name=IXContainer>Container</a>.  Containers contain Component objects that are to appear within the confines of the visible regions associated with the Containers.  In effect, the simple act of adding a Component to a Container causes the underlying window toolkit (such as Motif) to physically draw the Component in the Container's region (see <a href="http://java.sun.com:80/books/Series/Tutorial/ui/components/peer.html">Details of the Component Architecture</a>).  For example, an Applet object is a kind of Container associated with a rectangular region inside a web browser window (Applet is a subclass of Panel, which is a subclass of Container).  The init lifecycle method can be defined to add a few Component objects, thus, making them visible to the user:

<tt><pre>
class Counter extends java.awt.Applet {
    Button b;
    TextField tf;
    public void init() {
        b = new Button("Hit me");
        tf = new TextField("0");
        add(b);
        add(tf);
    }
}
</pre></tt>

<p>
The <em><a name="containment hierarchy">containment hierarchy</a></em> created by the Counter applet can be viewed as follows:

<p>
<center>
<img src=./images/CounterDiagram.gif>
</center>

<p>
This type of hierarchy diagram becomes a useful learning tool when you learn about partitioning the applet region with <a href="NestedPanels.html">nested containers</a> and when you learn about <a href="Events.html">events</a>.

<p>
The first big question people ask about Java GUI construction is "How do I get the widgets laid out the way I want?"  In other words, why is it that, in the Counter applet, the TextField appears to the right of the Button?  The first possibility that comes to mind is that components are placed at specific x,y coordinates.  While this approach works, it is tedious to specify coordinates for every Component and does not stretch or reposition the components according to different applet window sizes.  Java's approach is to use a layout manager for each Container object.

<p>
A layout manager is an object that positions and resizes the components in a Container according to some algorithm; for example, the <a href="FlowLayout.html">FlowLayout</a> layout manager lays out components from left to right until it runs out of room and then continues laying out components below that row.  FlowLayout is the default layout manager for applets and, therefore, the Button and TextField that were added appeared next to each other on a row; the Button is positioned on the left because it was added to the applet first.  If the applet region were more narrow than wide, then the HTML invocation:

<tt><pre>
&ltapplet code=Counter.class CODEBASE="/applets/magelang/AWT-Training/Examples/"
width=50 height=100>&lt/applet>
</pre></tt>

would result in a different physical layout even though the Java source code was not modified, nor recompiled:

<center>
<hr>
<applet code=Counter.class CODEBASE="/applets/magelang/AWT-Training/Examples/" width=50 height=60></applet>
<hr>
</center>

<p>
Rarely will one layout manager be sufficient to position all the components in your applet--the applet region will have to be broken down into subregions, each of them a Container with a layout manager.  The various <a href="NestedPanels.html">nested Container</a> objects will look just like Component objects and will be added to your applet in the same manner.

<p>
Now that you are familiar with how GUI components are created and placed in the applet region, you must consider the question:  "How do I make the components of my GUI respond to user stimuli?"  Another way to ask the same question is:  "Where do I define a method so that it is called when I push a certain Button object with the mouse?"   The answer is that you have a choice.  Either the Component that was activated responds, the Component's Container responds, or <a href="Events.html">both respond</a>.  The containment hierarchy illustrates this nicely:

<p>
<center>
<img src=./images/EventChain.gif>
</center>

<p>
The activated Component is normally given a chance to respond by calling its action method.  The default action method for Button and any Component is to do nothing but return false, which indicates that the Component did not handle the event.  Returning false from a Component event handler lets the event flow through to the enclosing Container.  For example, you can execute a code block upon a Button push in our Counter applet by defining an action method with the appropriate signature inside class Counter:

<tt><pre>
public boolean action(Event e, Object arg) {
    // get the text inside the TextField
    int v = Integer.parseInt(tf.getText());
    // increment its value and reset the TextField
    tf.setText(String.valueOf(v+1));
    return true;
}
</pre></tt>

<p>
The action method returns true to indicate that it has successfully handled the event.

<p>
Note that the action method of a Container will be called for any unhandled event generated for any contained Component.  In the Counter example, a TextField and a Button are present.  The Counter applet behavior is such that you want to include a statement in action to ignore events generated by the TextField (otherwise hitting return inside the TextField would increment it also).  The complete Counter applet source is:

<tt><pre>
import java.awt.*;
class Counter extends java.awt.Applet {
    Button b;
    TextField tf;
    public void init() {
        b = new Button("Hit me");
        tf = new TextField("0");
        add(b);
        add(tf);
    }
    public boolean action(Event e, Object arg) {
        if ( e.target != b ) return false;
        int v = Integer.parseInt(tf.getText());
        tf.setText(String.valueOf(v+1));
        return true;
    }
}
</pre></tt>

<p>
Shouldn't the behavior of a Button press be encapsulated in the Button object rather than having one giant action method in the applet? What happened to object-oriented programming?  Yes, it is best to <a href="EncapsulatingBehavior.html">encapsulate the action method within a Component</a> by subclassing it to override action.

<p>
Up to this point, we have discussed the procedure for creating GUIs using widgets such as buttons and for displaying information with text fields.  But, what about drawing simple lines and displaying GIF files?  An applet can draw a number of shapes such as lines, circles, and rectangles using the Graphics class.  The Graphics class represents a graphics context or perspective that also allows you to display text and images.  For example, the applet lifecycle method paint is passed the Graphics context of the overall applet.  
<p>
Here is an applet that displays some text and draws a line from the upper-left corner to 50 pixels over and 30 pixels down:

<center>
<hr>
<applet code=DrawApplet.class CODEBASE="/applets/magelang/AWT-Training/Examples/" width=100 height=40></applet>
<hr>
</center>

<p>
The corresponding Java code is very simple:

<tt><pre>
import java.applet.*;
import java.awt.*;
public class DrawApplet extends Applet {
    public void paint(Graphics g) {
        g.drawLine(0,0,50,30);
        g.drawString("0,0 to 50,30", 35,15);
    }
}
</pre></tt>

<p>
GIF files can be displayed by loading and then drawing them, such as in the following applet that displays Duke:

<center>
<hr>
<applet code=SimpleImage.class
CODEBASE="/applets/magelang/AWT-Training/Examples/" width=65 height=65></applet>
<hr>
</center>

<p>
The source code gets an image from the images subdirectory of the directory where the SimpleImage.class is stored, and draws it when the applet is
told to refresh the screen (in paint).

<tt><pre>
import java.applet.Applet;
import java.awt.*;
public class SimpleImage extends Applet {
    Image im;
    public void init() {
        // getCodeBase returns directory where SimpleImage
        // came from.
        im = getImage(getCodeBase(), "images/duke.gif");
    }
    public void paint(Graphics g) {
        // display upper-left of image at applet upper-left.
        // 'this' argument is the observer; drawImage
        // wants to know who to notify when image is
        // complete (images are loaded in drawImage)
        g.drawImage(im, 0, 0, this);
    }
}
</pre></tt>

See also <a href="http://java.sun.com:80/books/Series/Tutorial/ui/drawing/overview.html">Overview of AWT Graphics Support</a>.
</TD>
</TR>
</TABLE>

<!--
        This table is for everything that goes under the 
        navbar, it is a full screen table. Use this table 
        ONLY for full screen width tables like an event 
        hourly schedule.
-->

<br clear=left>
<TABLE ALIGN=left>

<tr>
<td WIDTH=600 align=right>

<!--Last Modified and copyright message

    Please modify the date whenever significant changes are made to 
    a page; leave the copyright alone
-->

</td>
</tr>
</TABLE>

</BODY>
</HTML>
