How to drag and drop with
Java 2 - JavaWorld - March 1999
Tutorial Details:
How to drag and drop with Java 2, Part 1
How to drag and drop with Java 2, Part 1
By: By Gene De Lisa
Explore the Java platform's new drag and drop classes
f you've ever selected a file icon in a filesystem browser like Windows Explorer and dragged it to an icon representing another directory (and it's likely you have), you've already used drag and drop to transfer data. If you'd like to use Java to transfer data, read on!
Java 2 (formerly JDK 1.2) introduced the ability to transfer data using the familiar drag and drop (D&D) metaphor. In Java 2, D&D utilizes the underlying data-transfer mechanism introduced in JDK 1.1 ( java.awt.datatransfer ) for use with the clipboard. Although this article discusses D&D operations in the context of GUI components, the specification includes no restrictions that prevent direct programmatic operations.
To develop the D&D metaphor, Java 2 defines several new classes in package java.awt.dnd . Please note: The GUI components used in this article are Swing components. In actuality, any subclass of java.awt.Component may be used.
First, we'll look at how a GUI component representing the data source of a D&D operation maintains an association with a java.awt.dnd.DropSource object.
Second, we'll examine how another GUI component representing the destination of the data of a D&D operation maintains an association with a java.awt.dnd.DropTarget object.
Finally, we'll wrap up with a java.awt.datatransfer.Transferable object that encapsulates the data transferred between the DragSource and DropTarget objects.
To download the source code in either zip or tar formats, see Resources .
DataFlavors and actions
When the Transferable object encapsulates data, it makes the data available to DropTarget in a variety of DataFlavors . For a local transfer within the same JVM (Java virtual machine), Transferable provides an object reference.
However, for transfers to another JVM or to the native system, this wouldn't make any sense, so a DataFlavor using a java.io.InputStream subclass usually is provided. (While a discussion of data transfer classes is beyond the scope of this article, you will find a linked list of previous JavaWorld articles on this topic in the Resources section below.)
When invoking a drag and drop operation, you may request various drag and drop actions. The DnDConstants class defines the class variables for the supported actions:
ACTION_NONE -- no action taken
ACTION_COPY -- the DragSource leaves the data intact
ACTION_MOVE -- the DragSource deletes the data upon successful completion of the drop
ACTION_COPY or ACTION_MOVE -- the DragSource will perform either action requested by the DropTarget
ACTION_LINK or ACTION_REFERENCE -- a data change to either the source or the destination propagates to the other location
Creating a draggable component
For a GUI component to act as the source of a D&D operation, it must be associated with five objects:
java.awt.dnd.DragSource
java.awt.dnd.DragGestureRecognizer
java.awt.dnd.DragGestureListener
java.awt.datatransfer.Transferable
java.awt.dnd.DragSourceListener
The DragSource
A common way to obtain a DragSource object is to use one instance per JVM. Class method DragSource.getDefaultDragSource will obtain a shared DragSource object that is used for the lifetime of the JVM. Another option is to provide one DragSource per instance of the Component class. With this option, however, you accept responsibility for implementation.
The DragGestureRecognizer
The user gesture or set of gestures that initiates a D&D operation will vary per component, platform, and device:
Windows drag and drop gestures
Click left mouse button
Move
Control, left mouse button
Copy
Shift-Control, left mouse button
Link
Motif Drag and drop gestures
Shift, BTransfer (middle button)
Move
Control, BTransfer
Copy
Shift-Control, BTransfer
Link
A DragGestureRecognizer encapsulates these implementation details, shielding you from platform dependencies. The instance method dragSource.createDefaultDragGestureRecognizer() will obtain a recognizer and associate it with a component, action, and DragGestureListener .
This example creates a subclass of a Swing label (JLabel). In its constructor, the necessary classes and associations are made for it to act as a drag source for either a copy or move operation. We'll discuss listeners next. Here's the first step in making any draggable component:
public class DragLabel extends JLabel {
public DragLabel(String s) {
this.setText(s);
this.dragSource = DragSource.getDefaultDragSource();
this.dgListener = new DGListener();
this.dsListener = new DSListener();
// component, action, listener
this.dragSource.createDefaultDragGestureRecognizer(
this, DnDConstants.ACTION_COPY_OR_MOVE, this.dgListener );
}
private DragSource dragSource;
private DragGestureListener dgListener;
private DragSourceListener dsListener;
}
The DragGestureListener
When the DragGestureRecognizer associated with the GUI component recognizes a D&D action, it messages the registered DragGestureListener . Next, the DragGestureListener sends the DragSource a startDrag message telling it to initiate the drag:
interface DragGestureListener {
public void dragGestureRecognized(DragGestureEvent e);
}
When the DragSource receives the startDrag message, it creates a DragSourceContext context object. This object tracks the state of the operation by listening to a native DragSourceContextPeer . In this situation, the DragSource may be obtained from the Event object or by an instance variable.
The particular DragSourceListener that will be informed during the progress of the D&D operation is specified as a formal parameter to dragGestureRecognized . The initial drag cursor that shows the preliminary state of the D&D operation is also specified as a parameter. If the draggable component cannot accept drops, the initial cursor should be DragSource.DefaultCopyNoDrop .
If your platform allows it, you may specify an optional "drag image" to be displayed in addition to the cursors. Win32 platforms, however, do not support drag images.
A Transferable object encapsulates the data -- most likely associated with the Component (that is, the label's text) -- that will be transferred. Here's how to start a drag:
public void dragGestureRecognized(DragGestureEvent e) {
// check to see if action is OK ...
try {
Transferable transferable = ...
//initial cursor, transferable, dsource listener
e.startDrag(DragSource.DefaultCopyNoDrop, transferable, dsListener);
// or if dragSource is an instance variable:
// dragSource.startDrag(e, DragSource.DefaultCopyNoDrop, transferable,
dsListener);
}catch( InvalidDnDOperationException idoe ) {
System.err.println( idoe );
}
}
The Transferable object
The java.awt.datatransfer.StringSelection class works well for transfers within the same JVM but suffers from a ClassCastException when used in inter-JVM cases. To solve this problem, you'll have to provide a custom Transferable object.
The custom Transferable object creates instances of the DataFlavors it wishes to provide. The Transferable interface directs method getTransferDataFlavors() to return an array of these flavors. To this end, we create a java.util.List representation of this array to facilitate the implementation of isDataFlavorSupported(DataFlavor) .
This example provides two flavors. Since we're simply transferring text data, we can use the two predefined DataFlavor flavors. For local transfers (within the same JVM), we can use DataFlavor.stringFlavor . For nonlocal transfers, we prefer DataFlavor.plainTextFlavor , since its internal representation class is a java.io.InputStream .
Moreover, we could define our own DataFlavors to map to MIME types such as image/JPEG, or define custom-text charsets such as Latin-1; but we'll save that discussion for a future article.
Although the Transferable doesn't necessarily have to be a ClipboardOwner for drag and drop, enabling this functionality will make it available for clipboard transfers.
Let's see the definition of a simple Transferable for text data:
public class StringTransferable implements Transferable, ClipboardOwner {
public static final DataFlavor plainTextFlavor = DataFlavor.plainTextFlavor;
public static final DataFlavor localStringFlavor = DataFlavor.stringFlavor;
public static final DataFlavor[] flavors = {
StringTransferable.plainTextFlavor,
StringTransferable.localStringFlavor
};
private static final List flavorList = Arrays.asList( flavors );
public synchronized DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported( DataFlavor flavor ) {
return (flavorList.contains(flavor));
}
The Transferable provides the data for the flavors it supports via its getTransferData method. However, if an unsupported flavor is requested, an exception will be thrown. If a local (same JVM) transfer is requested via the StringTransferable.localStringFlavor , an object reference is returned. Note: Object references don't make sense outside of the JVM.
A subclass of java.io.InputStream should be provided for native-to-Java or inter-JVM requests.
For StringTransferable.plainTextFlavor requests, getTransferData returns a java.io.ByteArrayInputStream . Text data may have different character encodings as specified in the MIME specification. (For more on the MIME specification, see Resources .)
The DataFlavor should be queried for the encoding requested by the DropTarget . Common character encodings are Unicode and Latin-1 (ISO 8859-1).
Here's how the Transferable can provide text data in a variety of formats and encodings:
public synchronized Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(StringTransferable.plainTextFlavor)) {
String charset = flavor.getParameter("charset").trim();
if(charset.equalsIgnoreCase("unicode")) {
System.out.println("returning unicode cha
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: How to drag and drop with
Java 2 - JavaWorld - March 1999
View Tutorial: How to drag and drop with
Java 2 - JavaWorld - March 1999
Related
Tutorials:
|
Displaying 1 - 50 of about 3972 Related Tutorials.
|
Drag and Drop Example in SWT
;
Drag and Drop in Java - This section is going to illustrates you how to
create a program to drag and drop the tree item in Java...
Drag and Drop Example in SWT
Drag and Drop |
Mouse Drag and Drop
Mouse Drag and Drop
Mouse Drag and Drop...;
This section illustrates you how to drag and move mouse to draw a figure.
To draw a figure using drag and drop, we have used Rectangle2D class |
Drag and Drop components from one frame to another frame
;
Java code given below shows that how to drag and drop
component (drop down list...
Drag and Drop components from one frame to another frame
Drag and Drop components from one frame to another frame |
Drag Demo
Java: Example - DragDemo.java
Java NotesExample - DragDemo.java
Drag the ball around...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
Dojo drag and drop
Dojo drag and drop
Dojo drag and drop...;
In this section, you will learn about dojo drag and
drop.
Drag and Drop... the object to the
suitable destination.
Try Online: Drag and
Drop
Here |
Making a component drag gable in java
Swing Drag Drop,Making Component Draggable in Java,Drag and Drop Example...;
In this section, you will learn how to make a component draggable in java.
This program provides the drag and drop feature from one component to another |
How to design a water drop.
How to design a water drop.<
How to design a water drop.
 ...;
This example is about a water drop effect on the leaf,
you |
Java: String Exercise 2
Java: String Exercise 2
Java: String Exercise 2
Name ______________________
Assume the following:
String s, t, h, a;
String n, e;
int i;
h = "Hello";
s = " How are you |
Struts 2 Training
Struts 2 Training, Training for developing applications with Struts 2
Struts 2 Training
 ...;
The Struts 2 Training for developing |
Struts 2 Tutorials for Beginners, Struts 2 Tutorial
Struts 2 Tutorial,Struts2 Examples,Apache Struts 2 Tutorials - Free Java... on
Struts 2 framework.
Writing
Jsp, Java... we will see how to write code that
will generate Java Script code for client |
Struts 2 datetimepicker Example
will show you how to develop
datetimepicker in struts 2. Struts 2 uses the dojo... have studied how to use Struts 2
datepicker control.  ...
Struts 2 datetimepicker,Struts 2 datetimepicker Example,Datetimepicker
Struts |
Struts 2 Hello World Application Example, Learn how to develop Hello World application in struts 2.
Struts 2 Hello World,Struts Hello World,Developing Hello World
Application
Struts 2 Hello World - Developing... Hello World
application based on Struts 2 Framework. Our Struts 2 Hello |
Struts 2 Tutorial
Struts 2 Tutorial,Struts2 Examples,Apache Struts 2 Tutorials - Free Java... on
Struts 2 framework.
Writing
Jsp, Java... we will see how to write code that
will generate Java Script code for client |
Struts 2 Login Application
Struts 2 Login,Struts 2 Login Application,Struts 2 Application
Struts 2 Login Application
 ...;
Developing Struts 2 Login Application |
Using Ant Build Scripts to Drop Mysql Table
;
This example illustrates how to drop table through the build.xml file
by simply running...
Using Ant Build Scripts to Drop Mysql Table,ant tutorial
Using Ant Build Scripts to Drop Mysql Table
  |
Choice Option (Combo) In Java
;
In this section, you will learn how to create Drop-Down
List... the
procedure of constructing a drop down list in java by using java awt.
There is a program...
Choice Option (Combo),Java Combo Box Program,Java Combo Box Example,Choice |
Struts 2 File Upload
;
In this section you will learn how to write program in
Struts 2 to upload the file...
Struts 2 File Upload
Struts 2 File Upload... file in any directory on the server machine.
The Struts 2 FileUpload component can |
Struts 2 Validation Example
application java script can be
added to the jsp page or in action class, but Struts 2... section we will see
how to generate client side validation code).
The Struts 2...
Struts 2 Validation,Struts 2 Validation Example |
Running and Testing Struts 2 Login application
. In the next section we will show you how
to add client side Java Script...
Running Struts 2 Login Example Program
Running and Testing Struts 2 Login application
  |
How to create LineDraw In Java
LineDraw in Java,Create Line Draw in Java,How to Create Line Draw in Java
How to create LineDraw In Java
 ...;
Introduction
This is a simple java program . In this section, you
will learn how |
Java Struts 2 Programmer
Java Struts 2 Programmer
Java Struts 2 Programmer...;
Position Vacant: Java Struts 2 Programmer ...;
Reference ID: Java Struts 2 Programmer
  |
Java Interview Questions - Page 2
:
1. The Java Virtual Machine (Java VM)
2. The Java...
Java Interview Questions,interview questions java
Java Interview Questions - Page 2
  |
How to Create CurveDraw In Java
Create CurveDraw in Java,Create Curve Draw Example Java,How to Draw Curve in Java Using Awt
How to Create CurveDraw In Java...;
Introduction
In this section, you will learn how to create CurveDraw |
Struts 2 Date Examples
available in the Struts 2 Framework. After reading the tutorials
you will lean how... how to develop datetimepicker in struts 2.
Struts 2 uses the dojo toolkit...
Struts 2 Date,Struts 2 Date Examples
Struts 2 Date |
Struts 2 Date Examples
available in the Struts 2 Framework. After reading the tutorials
you will lean how... how to develop datetimepicker in struts 2.
Struts 2 uses the dojo toolkit...
Struts 2 Date,Struts 2 Date Examples
Struts 2 Date |
String Exercise 2 - Answers
Java: String Exercise 2 - Answers
Java: String Exercise 2 - Answers
Name ______________________
Assume the following:>
String s, t, h, a;
String n, e;
int i;
h = "Hello";
s = " How |
Programming: Initials 2
Java: Programming: Initials 2
Java: Programming: Initials 2
Name... the user enters a single name (eg, Prince).
New Java features. The purpose |
Struts 2 Format Examples
:
In this section you learnt how to use Struts 2 Format
functionality...
Struts 2 Format,Struts 2 Format Examples
Struts 2...;
In this section you will learn how to format Date and numbers |
Introduction to Maven 2
Introduction to Maven 2
Introduction to Maven 2... but not all plugins that exists for maven1 are
ported yet. Maven 2 is expected... to use maven as the core build system
for Java development in one project and a multi |
Java Programming Books
This guide describes how to create and run Java? 2 Platform, Enterprise...;
Sams Teach Yourself Java 2 in 24 Hours... provide information on how to use individual Java technologies to write |
Free Java Books
Yourself Java 2 in 24 Hours
As the author of computer books, I spend a lot... multitier enterprise applications with the
Java TM 2 Platform, Enterprise... and the Java Blueprints program don't provide information on how to use individual Java |
How to design a remote of the game.
of the Remote:
1. Select Ellipse tool (U key) and drag a circle
2. Select pen tool (P... Ellipse tool with selected "5163B0" color and drag a
circle
2. Select Pen... this.
Ellipse tool:
1. Select Ellipse tool and drag a circle
2. Select Pen tool (P |
Struts 2 Features
Struts 2 Features
Struts 2 Features
 ... platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.
Some of the general features of the current Apache Strut 2 framework are given below |
How to use email validation check through java script in jsp page
How to use email validation check through java script in jsp page
How to use email validation check through java script in jsp page...;
This is detailed java code that explains how to use
java |
jQuery Drop Down Menu
jQuery Drop Down Menu
jQuery Drop Down Menu...;
In this JQuery tutorial we will develop a
program to make Drop Down menu
Steps to develop the Drop Down menu .
Step 1:
  |
Collections Exercise 2 - State Capitals
Java: Collections Exercise 2 - State Capitals
Java: Collections Exercise 2 - State Capitals
Name... codes.
Question: What data structure would be appropriate, and how could this data |
Client Side validation in Struts 2 application
Client Side validation in Struts 2 application
Client Side validation in Struts 2 application
 ...;
In this section we will see how |
How to use this keyword in java
This Keyword,Java This Keyword,Java 'This' Keyword,This Keyword Example in Java
How to use "this" keyword in java... of the program for the illustration of how to what is this
keyword and how to use |
Struts 2 - History of Struts 2
Struts 2 History
Struts 2 History
 ... is an open-source framework that is used for developing Java web application... and Servlet
based on HTML formats and Java code. Strut1 with all standard Java |
Struts 2 Architecture - Detail information on Struts 2 Architecture
Struts 2 Architecture,Struts Architecture
Struts 2...;
Struts and webwork has joined together to develop the
Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development |
How to Create JSP Page
How to Create JSP Page
How to Create JSP Page...;
In this section we will show you how you can create JSP page... can be
used.
In this example I will show you how to create a simple JSP page |
How to Create Circle In Java
How to Create Circle in Java,Create Circle Using Java Awt,Create Circle Example in Java
How to Create Circle In Java... will learn how to create Circle Diagram. The java circle is the most
fundamental |
Java Swing
in java. This program provides the drag and drop feature
from one component... from one frame to another frame
Java code given below shows that how to drag... through drag and drop, copy, paste, cut etc.
Data transfer works between Swing |
New to Java?
explained how to learn Java and master the Java technologies.
Java is a vast... the world in different languages. Drag and Drop
is another feature of JFC...
New to Java - New to java tutorial
New to Java |
New to Java?
explained how to learn Java and master the Java technologies.
Java is a vast... the world in different languages. Drag and Drop
is another feature of JFC...
New to Java - New to java tutorial
New to Java |
Java API
;
javax.accessibility
Drag n Drop
 ... of J2SE 1.4 and later, JSSE 1.0.3 is an optional package to the Java 2 SDK...
Java API, what is java api?
Java API |
How to use foreach loop in velocity
How to use foreach loop in velocity
How to use...;
This
Example shows you how
to use foreach...().
2:- Create object of
VelocityContext Class.
3:- Create Template
class |
Tiger XSLT Mapper
are automatically created and can be edited using the drag-and-drop
visual interface |
How to Make a Pdf and inserting data
How to Make a Pdf and inserting data
How to Make... how we can make a pdf
file and how we can insert a data into the pdf file...;%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display |
How to Java Program
How to Java Program
How to Java Program... how to learn Java and become a master
of the Java technologies.
Java is a high...;
If you are beginner in
java , want to learn and make career |
|
|
|