    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Software Development with Java User Interfaces II</title>
        <link>https://members.accu.org/index.php/journals/874</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 11, #3 - Apr 1999 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c132/">113</a>
                    (22)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c132-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c132+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Software Development with Java User Interfaces II</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 April 1999 13:15:30 +01:00 or Sat, 03 April 1999 13:15:30 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="section" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a></h2>
</div>
<p>A man with only a very short time to live has a choice to eat
meat or drink wine. He has to eat right now, right this minute, and
whatever he consumes, he knows that it will be his last action. If
he drinks the wine first then he misses the chance to savour the
succulent tender red meat, but if he devours the meat he will
definitely miss the fine white wine. I am going to serve a lot red
meat in this article and hopefully you will survive to drink the
white wine only because C Vu is a bimonthly!</p>
<p>Java only supports single inheritance it does not multiple
inheritance. Every object in Java extends (derives from) the
<tt class="classname">Object</tt> class. However the Java language
does support an elegant alternative to multiple inheritance called
<span class="emphasis"><em>Interfaces</em></span>. An interface
type acts very much like a class type. You can declare variables to
be of an interface type. You can pass them to methods too and they
can even be a type returned from a method. However the key
difference between a Java class and a Java interface is that an
interface defines a <span class=
"emphasis"><em>contract</em></span>. What does this contract mean?
The interface's contract is very much like a big badge which
somebody in a superstore wears which says, &quot;Hi, I am your faithful
superstore helper, I am a class type X which is capable of doing Y
just for you.&quot; The interface in our Java superstore promises, in
other words, to act out a certain behaviour or a set of behaviours.
We say that class X <span class=
"emphasis"><em>implements</em></span> a particular service Y. A
Java interface is also similar to an abstract class, because it
does not contain implementation code just the heading of methods.
Here is an example of a Java interface called <tt class=
"classname">Flyable</tt>.</p>
<pre class="programlisting">
Interface Flyable {
  // assume gravity is 9.81g
  void fly( float drag, float thrust, float lift );
}
</pre>
<p>An interface is defined with the keyword <tt class=
"literal">interface</tt> and list of methods with no bodies. The
methods of any interface are <span class=
"emphasis"><em>always</em></span> public, because other classes
would not be able use it if this was otherwise.</p>
<p>In order to use any interface it must be specified as part of
the class definition. The clause <tt class=
"literal">implements</tt> is used after the <tt class=
"literal">extends</tt> keyword. This is equivalent to saying, &quot;I,
class X, promise to acknowledge and uphold the contract, Y&quot; which
is exactly another way of writing the above assertion. The next
step is to write the bodies of <span class=
"emphasis"><em>all</em></span> the methods in the interface
definition. An interface implementation is not inheritable, each
new subclass requires its own method bodies. Here is an <tt class=
"classname">Aeroplane</tt> class that implements the <tt class=
"classname">Flyable</tt> interface.</p>
<pre class="programlisting">
class Aeroplane implements Flyable {
  boolean propellerRunning;

  public void fly( float drag, float thrust, float lift )
  {
    if (propellerRunning) { 
       //...fly
    }
  }
  public boolean isPropellerRunning() 
    { return (propellerRunning); }
  public void setPropellerRunning( boolean flag ) 
    { propellerRunning = flag; }
}
</pre>
<p>The advantage of Java interfaces are the clear separation of
interface and implementation, since code can refer to interface
types instead of fixed class names. It therefore lends itself to
the generic containers like those in the Collection API for
example, and without interfaces much of event handling for AWT
component would be more difficult to write.</p>
<p>In my last article, the VideoRecorder1 application displayed
correctly, but it was not complete. It did not respond to user
input. The AWT defines a number of class events in the package
<tt class="classname">java.awt.event</tt>. <tt class=
"classname">MouseEvent</tt>, <tt class=
"classname">MouseMotionEvent</tt>, <tt class=
"classname">KeyEvent</tt>, <tt class="classname">FocusEvent</tt>,
and <tt class="classname">ActionEvent</tt> are examples. For the
purpose of the Digital Video Recorder example it would be nice to
add communications to the <tt class="classname">Button</tt>
components. All AWT Components communicate by sending events. In
Java vernacular, we developer talk about &quot;firing&quot; events and
&quot;receiving&quot; (or &quot;handling&quot;) them. All AWT Events are just ordinary
Java object classes; no special syntax or constructs are required
whatsoever.</p>
<p>An event is fired from a <span class="emphasis"><em>source
object</em></span>, say an AWT Button, to one or more <span class=
"emphasis"><em>listeners</em></span> (also known as receivers),
obviously our application. (You may be already be familiar with
C/C++ callbacks in X/OSFMotif or MFC GUI Programming, please note
that the Java AWT approach is much better, because it applies the
Publish/Subscribe design pattern directly.) A listener <span class=
"emphasis"><em>implements</em></span> particular event handling
methods in this way. It can then respond to an event from the
source object. However in order for a listener to receive any
events, it must first register itself with the source of the
event.</p>
<p>When an AWT Button is pressed and depressed it fires a
<tt class="classname">java.awt.event.ActionEvent</tt> to all its
registered action event listeners. The event is delivered to any
object class that implements the <tt class=
"classname">java.awt.event.ActionListener</tt> interface. The
definition of this interface is show below:</p>
<pre class="programlisting">
interface ActionListener extends java.util.EventListener {
    pulic void actionPerformed( ActionEvent e );
}
</pre>
<p>The event is passed to method called <tt class=
"methodname">actionPerformed()</tt> as a parameter. Similar method
declaration exists for the other listeners and event types like
<tt class="classname">KeyListener</tt> and <tt class=
"classname">KeyEvent</tt>. The <tt class=
"classname">ActionListener</tt> is sub-interface of <tt class=
"classname">java.util.EventListener</tt>, but <tt class=
"classname">EventListener</tt> is only an empty class definition,
and it is used only for type identification. The <tt class=
"classname">ActionEvent</tt> is derived from the <tt class=
"classname">AWTEvent</tt> class. The <tt class=
"classname">AWTEvent</tt> class maintains an important property
called <tt class="varname">source</tt>, which is a reference to the
object that fired the event. Thus a listener can establish what
component object fired the event by calling the <tt class=
"methodname">getSource()</tt> method.</p>
<p>Okay that takes care of destination end of the stick, but what
about the source end. The AWT Button has two methods that register
and unregister action event listeners. These are:</p>
<pre class="programlisting">
public void addActionListener( ActionListener listener );
public void removeActionListener( ActionListener listener );
</pre>
<p>Here is an example that puts all the above together and it
should be much clearer now:</p>
<pre class="programlisting">
public class AReceiver implements ActionListener {
    Button  aButton;

    public AReceiver() {
  ...
  aButton = new Button(&quot;Press Me Now!&quot;);
  aButton.addActionListener(this);
   ...
    }

    public void actionPerformed( ActionEvent e ) {
  Object src = e.getSource();
  if (src == aButton) 
     System.out.println(&quot;A button was activated.&quot;);
   }
}
</pre>
<p>Note that the <tt class="classname">AReceiver</tt> class
registers itself with the button in the constructor, because it is
an <tt class="classname">ActionListener</tt> type. It contracts to
implement the behaviour <tt class=
"methodname">actionPerformed()</tt>. In the handler method the
reference to the original button is required, so that it possible
to test the source of the event.</p>
<p>Going back to our DVR example we simply now have to make the
<tt class="classname">VideoRecorder</tt> class become an <tt class=
"classname">ActionListener</tt> as well. We implement the
<tt class="classname">ActionListener</tt> interface, and once that
is done write body of the <tt class=
"methodname">actionPerformed()</tt> method . We register our class
with all the buttons created in the constructor. After all changes
are made the <tt class="classname">VideoRecorder</tt> class will
now respond to user input events.</p>
<pre class="programlisting">
// VideoRecorder2.java
import java.awt.*;
import java.awt.event.*;

public class VideoRecorder2 extends Frame
implements ActionListener
{
    // Member variables
    protected Button bt_eject, bt_stop, bt_rec, bt_rew;
    protected Button bt_play, bt_ffwd, bt_pause;
    
    public VideoRecorder2( String title )
    {
  // pass the title to the superclass frame class
  super(title);
  setLayout( new BorderLayout() );
  ...
  // Create VCR buttons 
  bt_eject = new Button(&quot;Eject&quot;);
  ...
  bt_eject.addActionListener(this);  
  ...
    }

public void actionPerformed( ActionEvent e ) 
    {
  // Event listener for ActioEvents
  Object src = e.getSource();
  if (src == bt_eject )
      System.out.println(&quot;Tape ejected!&quot;);
  else if (src == bt_stop )
      System.out.println(&quot;Tape stopped&quot;);
...
  else if (src == bt_play )
      System.out.println(&quot;Tape playing&quot;);
  ...
    }
    
    public static void main( String [] args )
    {
  VideoRecorder2 dvr = new VideoRecorder2(&quot;ACCU Digital Video Recorder&quot;);
  dvr.pack();
  dvr.show();
    }
</pre>
<p>Notice in the <tt class="methodname">actionPerformed()</tt>
method of <tt class="classname">VideoRecorder2</tt> the source
object is used in a chained comparison to tell which button
originated the action event. AWT Buttons support an alternative
method to identify the source object known as <span class=
"emphasis"><em>action commands</em></span>, which is simply a fancy
name for an ordinary string. The action command associated with an
AWT Button can be accessed and modified with:</p>
<pre class="programlisting">
public void setActionCommand( String cmd );
public String getActionCommand();
</pre>
<p>The <tt class="classname">ActionEvent</tt> also supports
retrieval of the action command string as a property of the action
event with the method <tt class=
"methodname">getActionCommand()</tt>. With this information we can
write different constructor and receiver methods.</p>
<pre class="programlisting">
public class VideoRecorder3 extends Frame
implements ActionListener
{
    // Member variables
    protected Button bt_eject, bt_stop, bt_rec, bt_rew;
    protected Button bt_play, bt_ffwd, bt_pause;
    
    public VideoRecorder3( String title )
    {
  // pass the title to the superclass frame class
  super(title);  
  setLayout( new BorderLayout() );
  
  // Create VCR buttons 
  bt_eject = new Button(&quot;Eject&quot;);
  ...
  bt_eject.setActionCommand(&quot;eject&quot;);
  bt_eject.addActionListener(this);
   }

   public void actionPerformed( ActionEvent e ) 
   {
  // Event listener for ActioEvents
  String cmd = e.getActionCommand();
  if (cmd.equals(&quot;eject&quot;) )
      System.out.println(&quot;Tape ejected!&quot;);
  else if (cmd.equals(&quot;stop&quot;) )
      System.out.println(&quot;Tape stopped&quot;);
  ...
  else if (cmd.equals(&quot;play&quot; ) )
      System.out.println(&quot;Tape playing&quot;);
  ...
   }
}
</pre>
<p>Why should anyone use action commands? Because it further
decouples the Buttons from the listener code.</p>
<p>We could throw away the class members <tt class=
"varname">bt_eject</tt>, <tt class="varname">bt_stop</tt>, and
<tt class="varname">bt_play</tt> etc. or move them all inside the
main constructor as normal automatic variables.</p>
<p>Did you understand all of that? Suppose later on after
developing our Digital Video Recorder for sometime, we decided to
add a <tt class="classname">Menubar</tt>, and a drop down
<tt class="classname">Menu</tt> with <tt class=
"classname">MenuItem</tt>s for stopping and playing. (A <tt class=
"classname">MenuItem</tt> is similar to a Button component in
behaviour and attributes.) We would have two ways for the DVR to
play a video: either pressing &amp; depressing the DVR play button
directly or navigating the menubar and its drop down menus. There
would be more than one event source that produce a play <tt class=
"classname">ActionEvent</tt>. Consequently we would need to store a
reference to the menu item variable in our source code somewhere.
But where and how should we store this variable reference? The
logic of the receiver method would become more complicated as a
result. Of course this becomes tedious if we decide, still later
on, to have more than two play action event sources in our code.
Comparing object references and maintaining them would be time
consuming and inefficient, whereas the equivalent action command
string can be stored in both the menu items and the DVR buttons. In
other words there is one event handler in the source code receiving
events with <span class="emphasis"><em>shared</em></span> messages
from multiple sources. Most of the time we are not concerned what
the source is anyway, we are only concerned with the context of
message itself which is simply says, &quot;Play it again, Sam&quot;.</p>
<pre class="programlisting">
void createMenu() {
Menu menu = new Menu(&quot;VCR Controls&quot;);
MenuItem mi_play = new MenuItem(&quot;Play&quot;);
mi_play.addActionListener( /* VCR Object */ );
mi_play.addActionCommand(&quot;play&quot;);
menu.add(mi_play);
}
</pre>
<p>Last but not least the source code is available from my home
page on Demon Internet <a href=
"http://www.xenonsoft.demon.co.uk/accu.html" target=
"_top">http://www.xenonsoft.demon.co.uk/accu.html</a> where you can
also retrieve a version of the DVR that uses a custom AWT component
called the <tt class="classname">ImageButton</tt>. The standard AWT
does not have such a component that displays a GIF/JPEG image and a
text label together. The component makes use of the package
<tt class="classname">java.awt.image</tt> and the classes
<tt class="classname">java.awt.Image</tt>, <tt class=
"classname">java.awt.Canvas</tt> , and <tt class=
"classname">java.awt.MediaTracker</tt>.</p>
<p>Drink the wine quickly now, and have fun with AWT and Java.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
