Java Reference
In-Depth Information
Cutting and Pasting Scribbles
Example 13-3 is a Swing application that allows the user to scribble with the
mouse and then transfer scribbles using cut-and-paste. It uses the Scribble class
defined in Example 13-2 to store, draw, and transfer the scribbles. The cut-and-
paste functionality is implemented in the cut() , copy() , and paste() methods,
which the user accesses through a popup menu. Notice how the paste() method
first attempts to transfer the data using the custom Scribble data flavor; if that
fails, it tries again using the predefined string data flavor. To test the program, run
two copies of it and transfer scribbles back and forth between the two copies.
Example 13−3: ScribbleCutAndPaste.java
package com.davidflanagan.examples.datatransfer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.datatransfer.*; // Clipboard, Transferable, DataFlavor, etc.
/**
* This component allows the user to scribble in a window, and to cut and
* paste scribbles between windows. It stores mouse coordinates in a Scribble
* object, which is used to draw the scribble, and also to transfer the
* scribble to and from the clipboard. A JPopupMenu provides access to the
* cut, copy, and paste commands.
**/
public class ScribbleCutAndPaste extends JComponent
implements ActionListener, ClipboardOwner
{
Stroke linestyle = new BasicStroke(3.0f); // Draw with wide lines
Scribble scribble = new Scribble();
// Holds our scribble
Scribble selection;
// A copy of the scribble as cut
JPopupMenu popup;
// A menu for cut-and-paste
public ScribbleCutAndPaste() {
// Create the popup menu.
String[] labels = new String[] { "Clear", "Cut", "Copy", "Paste" };
String[] commands = new String[] { "clear", "cut", "copy", "paste" };
popup = new JPopupMenu();
// Create the menu
popup.setLabel("Edit");
for(int i = 0; i < labels.length; i++) {
JMenuItem mi = new JMenuItem(labels[i]); // Create a menu item
mi.setActionCommand(commands[i]);
// Set its action command
mi.addActionListener(this);
// And its action listener
popup.add(mi);
// Add item to the menu
}
// Finally, register the popup menu with the component it appears over
this.add(popup);
// Add event listeners to do the drawing and handle the popup
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
popup.show((Component)e.getSource(),
e.getX(), e.getY());
else
scribble.moveto(e.getX(), e.getY()); // start new line
}
Search WWH ::




Custom Search