home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Platinum Edition Using HTML 4, XML, and Java 1.2
(Publisher: Macmillan Computer Publishing)
Author(s): Eric Ladd
ISBN: 078971759x
Publication Date: 11/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Understanding Swing Events

Earlier in this chapter, in “Using the Abstract Windowing Toolkit,” we introduced the delegation event model and talked about low-level and semantic events. Swing has its own event package for Swing-specific events. Use the javax.swing.event package for the event listeners and the events themselves; the event sources are the Swing components. The following is a list of the Swing event classes—DocumentEvent is an interface—and their meanings:


NOTE:  Many Swing events, such as those that refer to the “model,” assume that you’re using the MVC pattern. Read the Swing documentation on MVC or Chapter 13 of Using Java 1.2 before attempting to use these Swing events.
  AncestorEvent—Ancestor added, moved, or removed.
  ChangeEvent—A component has had a state change.
  DocumentEvent—A document has had a state change.
  ListDataEvent—Contents of a list have changed, or an interval has been added or removed.
  ListSelectionEvent—The selection on a list has changed.
  MenuEvent—A menu item has been selected or posted, deselected, or canceled.
  TableColumnModelEvent—The model for a table column has changed.
  TableModelEvent—The model for a table has changed.
  TreeExpansionEvent—A tree node has been expanded or collapsed.
  TreeModelEvent—A tree model has changed.
  TreeSelectionEvent—The selection in a tree has changed status.


NOTE:  Sun divides events into two categories—semantic events and low-level events. Usually you’ll get a better, more portable interface by listening for semantic events such as the ActionEvent. If you need special behavior, however, you can listen for low-level events such as mouse clicks and key presses. Refer back to Listing 37.6—TRaceApplet.java—to see how to use low-level events. Line 72 (copied below) constructs a new TMouseAdapter:

TMouseAdapter aMouseAdapter = new TMouseAdapter();

That adapter is defined in lines 202 to 215 (shown below). When the adapter “hears” a mouse press, it consumes the event (line 207—copied below)

anEvent.consume();

and toggles fThreadSuspended; if the thread was suspended, it is now unsuspended, and vice versa.


   class TMouseAdapter extends java.awt.event.MouseAdapter
   {
     public synchronized void mousePressed(
 ⇒java.awt.event.MouseEvent anEvent)
     {
       anEvent.consume();
       fThreadSuspended = !fThreadSuspended;
       if (!fThreadSuspended)
         synchronized (fMonitorThread)
         {
           fMonitorThread.notifyAll();
         }
     }
   }

• To learn more about TRaceApplet.java, see “Sample Applets” on p. 1001.

Drag and Drop

In the latest version of the JDK, all drag-and-drop (DnD) operations (for both Swing and AWT components) are supported through the interface java.awt.dnd. Listing 38.14 shows a typical DnD program.


NOTE:  When a class implements an interface, the class must provide an implementation of every method in the interface. To implement a drag-and-drop target, a class must implement DropTargetListener. As shown in Listing 38.14, most of the work is done in dragEnter() and drop().

Listing 38.14 DnDTest.javaAn Implementation of a DropTargetListener


import java.awt.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;

public class DnDTest extends Frame implements DropTargetListener {

  DropTarget fTarget;
  TextArea fTextArea;

  public DnDTest () {
    fTextArea = new TextArea(“Grab some text and \npull it over here!”);
    fTarget = new DropTarget(text, DnDConstants.ACTION_COPY, this);
    fTarget.setActive (true);
    add (“Center”, fTextArea);
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
  }

  public static void main (String args[]) {
    DnDTest theFrame = new DnDTest();
    theFrame.setSize (400, 200);
    theFrame.setVisible (true);
  }

// required methods in DropTargetListener
  public  void dragEnter (DropTargetDragEvent dtde) {
    System.out.println (“dragEnter”);

    // use the DropTargetDragEvent to find out what flavors are offered
    DataFlavor df[] = dtde.getCurrentDataFlavors();
    for (int i = 0; i < df.length; i++)   {
      if (df[i].equals (DataFlavor.plainTextFlavor)) {

        // if the flavor is plain text, accept the drag
        dtde.acceptDrag (DnDConstants.ACTION_COPY);
        return;
      }
    }
    // otherwise reject this drag
    dtde.rejectDrag ();
  }

  public  void dragOver (DropTargetDragEvent dtde) {

    // dragOver is called repeatedly while the cursor is over
    // the target. Uncomment the println to see how often this
    // method is called.
    //System.out.println (“dragOver”);
  }

  public void dropActionChanged(DropTargetDragEvent dtde) { 
    System.out.println(“dropActionChanged”);
  }

  public  void dragScroll (DropTargetDragEvent dtde) {
    System.out.println (“dragScroll”);
  }

  public  void dragExit (DropTargetEvent dte) {
    System.out.println (“dragExit”);
  }

  public  void drop (DropTargetDropEvent dtde) {
    dtde.acceptDrop (DnDConstants.ACTION_COPY);
    System.out.println (“dropped”);
    Transferable theTransferable = dtde.getTransferable();
    DataFlavor df[] = dtde.getCurrentDataFlavors();
    Object theObject = null;

    try {

      // search through the flavor looking for plain text
      // when you find it get the associated data and stuff
      // it into the Object.
      for (int i = 0; i < df.length; i++)   {
        if (df[i].equals (DataFlavor.plainTextFlavor)) {
          theObject = theTransferable.getTransferData(df[i]);
        }
      }

      // if the data comes from outside the JVM, it comes in
      // on an InputStream. Read in the stream.
      if (theObject != null && theObject instanceof InputStream) {
        InputStream theInputStream = (InputStream) theObject;
        StringBuffer theStringBuffer = new StringBuffer();
        byte[] aBuffer = new byte[64];
        int theCount = theInputStream.read(aBuffer);
        while (theCount != -1) {
          // keep stuffing data into the string buffer
          theStringBuffer.append (new String (aBuffer, 0, theCount));
          theCount = theInputStream.read(aBuffer);
        }
        // We’ve read in all the data. Now let’s use it
        theInputStream.close();
        fTextArea.setText (theStringBuffer.toString());
      }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
      try {
        fTarget.getDropTargetContext().dropComplete(true);
      } catch (Exception ignore) {}
    }
  }

// let’s handle a click on the window’s close box
  protected void processWindowEvent (WindowEvent e) {
    if (e.getID() == WindowEvent.WINDOW_CLOSING)
      System.exit(0);
    super.processWindowEvent (e);
  }
}


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.