Java Reference
In-Depth Information
Example 13−4: ScribbleDragAndDrop.java (continued)
}
});
drag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scribblePane.setDragMode(true);
}
});
group.add(draw); group.add(drag);
toolbar.add(draw); toolbar.add(drag);
frame.getContentPane().add(toolbar, BorderLayout.NORTH);
// Start off in drawing mode
draw.setSelected(true);
scribblePane.setDragMode(false);
// Pop up the window
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Exercises
13-1. Consider the
StringSelection
class: it implements the
Transferable
inter-
face for the
String
class and makes it easy to transfer strings between appli-
cations. Write a class named
SimpleSelection
that implements the
Trans-
ferable
and
ClipboardOwner
interfaces just as
StringSelection
does. The
constructor for your class should take an arbitrary serializable object as its
sole argument; this object is the “selection” it should transfer. Construct a
DataFlavor
based on the representation class of this object (see
Object.getClass()
) and implement the methods of the
Transferable
inter-
face using the
DataFlavor
you created.
Now modify Example 13-1 to use
SimpleSelection
to transfer
Integer
objects using cut-and-paste. Note that
SimpleSelection
will probably only
work for intraapplication cut-and-paste.
13-2. Modify Example 13-4 so that it supports cut-and-paste in addition to drag-
and-drop. Allow the user to select a scribble by double-clicking on it (see
MouseEvent.getClickCount()
). Allow the user to paste a scribble from the
clipboard using a menu item, mouse gesture, or keyboard event of your
choice. When the user double-clicks a scribble, highlight that scribble using
a different color and keep it highlighted until something else replaces it on
the clipboard.