Java Reference
In-Depth Information
Example 13−4: ScribbleDragAndDrop.java (continued)
else {
e.rejectDrop();
return;
}
// We've accepted the drop, so now we attempt to get the dropped data
// from the Transferable object.
Transferable t = e.getTransferable(); // Holds the dropped data
Scribble droppedScribble; // This will hold the Scribble object
// First, try to get the data directly as a scribble object
try {
droppedScribble =
(Scribble) t.getTransferData(Scribble.scribbleDataFlavor);
}
catch (Exception ex) { // unsupported flavor, IO exception, etc.
// If that doesn't work, try to get it as a String and parse it
try {
String s = (String) t.getTransferData(DataFlavor.stringFlavor);
droppedScribble = Scribble.parse(s);
}
catch(Exception ex2) {
// If we still couldn't get the data, tell the system we failed
e.dropComplete(false);
return;
}
}
// If we get here, we've got the Scribble object
Point p = e.getLocation(); // Where did the drop happen?
droppedScribble.translate(p.getX(), p.getY()); // Move it there
scribbles.add(droppedScribble);
// add to display list
repaint();
// ask for redraw
e.dropComplete(true);
// signal success!
}
// These are unused DropTargetListener methods
public void dragOver(DropTargetDragEvent e) {}
public void dropActionChanged(DropTargetDragEvent e) {}
/**
* The main method. Creates a simple application using this class. Note
* the buttons for switching between draw mode and drag mode.
**/
public static void main(String[] args) {
// Create a frame and put a scribble pane in it
JFrame frame = new JFrame("ScribbleDragAndDrop");
final ScribbleDragAndDrop scribblePane = new ScribbleDragAndDrop();
frame.getContentPane().add(scribblePane, BorderLayout.CENTER);
// Create two buttons for switching modes
JToolBar toolbar = new JToolBar();
ButtonGroup group = new ButtonGroup();
JToggleButton draw = new JToggleButton("Draw");
JToggleButton drag = new JToggleButton("Drag");
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scribblePane.setDragMode(false);
Search WWH ::




Custom Search