Drag on a JLabel

I've build a ImageButton component on top of a JLabel. Normally one would use JButton without borders and stuff, but under Nimbus there are margin (inset) issues and JLabel always works fine. So add a mouse listener and some highlight logic on the icon for mouse-over and he world looks fancy. All is good.
However, to create a more fancy GUI, I also want to be able to drag images around. Now, images shown in a JList work fine, because JList handles the DnD, but it does not render the way I want. So I want to use pure ImageButtons (with highlight behavior and click handling) in a normal layout (e.g. GridBag). This means I have to bolt on the Dnd myself.
This mean I could extend my component with " implements DragGestureListener, DragSourceListener" and get that to work, but that is pre 1.4. But I can't seem to figure out how to bolt on DnD in the "1.4+" way using the TransferHandler.
Does anyone have an example on own to add drag support to a JLabel?

Hm. So on first glance this seems to make a component "slide" visually (hence your remark about a layout manager ), but that is not what Java's Drag-and-Drop (DnD) is about. DnD basically is a visual cut/copy-paste; after starting a drag a Transferable is created (cut/copy), which represents the data this is copied/moved. The drop is equal to a paste. This whole concept is missing.
On the other hand, I have to think about that, just moving the component may also work just fine. Thanks for the suggestion at the very least!

Similar Messages

  • Drag and Drop Swing Components between two different Application Windows

    Hi!!!
    I tried the Dnd feature using the DnD api. It was a simple test, where I ahd two different app windows each made up of a JLabel. One I registered as drag component and the other as a drop component. the drop componenet(JLabel) does not have any text making it invisble to the eyes. When I drag the other JLabel to the drop window, the drop JLAbel takes the text value. I was successful so far.
    But can I do the same for any other Swing component in a scenario where when I drag the component, the component should have physically moved into the other window.
    any help on this with sample code will be greatly apprciated.
    Thanks in advance
    Suja

    Ok I found the answer to your problem. If you download the tutorial they have the code there it's in one folder. I hope this helps.
    http://java.sun.com/docs/books/tutorial/

  • Drag and Drop between two java applications

    Hi,
    I am trying to implement drag and drop between two instances of our java application. When i drop the content on the target, the data flavors are transmitted properly, but i get the exception :
    java.awt.dnd.InvalidDnDOperationException: No drop current
         at sun.awt.dnd.SunDropTargetContextPeer.getTransferData(SunDropTargetContextPeer.java:201)
         at sun.awt.datatransfer.TransferableProxy.getTransferData(TransferableProxy.java:45)
         at java.awt.dnd.DropTargetContext$TransferableProxy.getTransferData(DropTargetContext.java:359)
         at com.ditechcom.consulbeans.TDNDTree.drop(TDNDTree.java:163)
         at java.awt.dnd.DropTarget.drop(DropTarget.java:404)
         at sun.awt.dnd.SunDropTargetContextPeer.processDropMessage(SunDropTargetContextPeer.java:547)
    How can i fix this ?
    Thanks a lot,
    Karthik

    Play with this;-import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    // Credit to bbritna who I stole it from in the 'New To ..' Forum
    public class DragComps implements DragGestureListener, DragSourceListener,
                                         DropTargetListener, Transferable{
        static final DataFlavor[] supportedFlavors = { null };
        static{
              try {
                  supportedFlavors[0] = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
              catch (Exception ex) { ex.printStackTrace(); }
        Object object;
        // Transferable methods.
        public Object getTransferData(DataFlavor flavor) {
               if (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType))
             return object;
               else return null;
        public DataFlavor[] getTransferDataFlavors() {
               return supportedFlavors;
        public boolean isDataFlavorSupported(DataFlavor flavor) {
               return flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType);
        // DragGestureListener method.
        public void dragGestureRecognized(DragGestureEvent ev)    {
               ev.startDrag(null, this, this);
        // DragSourceListener methods.
        public void dragDropEnd(DragSourceDropEvent ev) { }
        public void dragEnter(DragSourceDragEvent ev)   { }
        public void dragExit(DragSourceEvent ev)        { }
        public void dragOver(DragSourceDragEvent ev) {
               object = ev.getSource(); }
        public void dropActionChanged(DragSourceDragEvent ev) { }
        // DropTargetListener methods.
        public void dragEnter(DropTargetDragEvent ev) { }
        public void dragExit(DropTargetEvent ev)      { }
        public void dragOver(DropTargetDragEvent ev)  {
               dropTargetDrag(ev); }
        public void dropActionChanged(DropTargetDragEvent ev) {
           dropTargetDrag(ev); }
        void dropTargetDrag(DropTargetDragEvent ev) {
               ev.acceptDrag(ev.getDropAction()); }
        public void drop(DropTargetDropEvent ev)    {
               ev.acceptDrop(ev.getDropAction());
                   try {
                       Object target = ev.getSource();
                      Object source = ev.getTransferable().getTransferData(supportedFlavors[0]);
                       Component component = ((DragSourceContext) source).getComponent();
                       Container oldContainer = component.getParent();
                       Container container = (Container) ((DropTarget) target).getComponent();
                       container.add(component);
                       oldContainer.validate();
                       oldContainer.repaint();
                       container.validate();
                       container.repaint();
                   catch (Exception ex) { ex.printStackTrace(); }
                   ev.dropComplete(true);
        public static void main(String[] arg)    {
              JButton button = new JButton("Drag this button");
              JLabel label = new JLabel("Drag this label");
              JCheckBox checkbox = new JCheckBox("Drag this check box");
              JFrame source = new JFrame("Source Frame");
              Container source_content = source.getContentPane();
              source.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              source_content.setLayout(new FlowLayout());
              source_content.add(button);
              source_content.add(label);
              JFrame target = new JFrame("Target Frame");
              Container target_content = target.getContentPane();
              target.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              target_content.setLayout(new FlowLayout());
              target_content.add(checkbox);
              DragComps dndListener = new DragComps();
              DragSource dragSource = new DragSource();
              DropTarget dropTarget1 = new DropTarget(source_content,
              DnDConstants.ACTION_MOVE, dndListener);
              DropTarget dropTarget2 = new DropTarget(target_content,
              DnDConstants.ACTION_MOVE, dndListener);
              DragGestureRecognizer dragRecognizer1 =
              dragSource.createDefaultDragGestureRecognizer(button,
              DnDConstants.ACTION_MOVE, dndListener);
              DragGestureRecognizer dragRecognizer2 =
              dragSource.createDefaultDragGestureRecognizer(label,
              DnDConstants.ACTION_MOVE, dndListener);
              DragGestureRecognizer dragRecognizer3 =
              dragSource.createDefaultDragGestureRecognizer(checkbox,
              DnDConstants.ACTION_MOVE, dndListener);
              source.setBounds(0, 200, 200, 200);
              target.setBounds(220, 200, 200, 200);
              source.show();
              target.show();
    }[/code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • StartDrag

    I have written code to drag and drop JLabels between various extended selection JLists, and for the main part it works fine. However fairly frequently the DragGestureListener is not invoked when I suspect it should be, e.g. the mouse button is down and the mouse is moved but startDrag() isn't invoked because the DragGestureRecognizer hasn't recognized this.
    Another, presumably related side effect, is that sometimes the DropTargetListener.drop() method is not invoked when the mouse button is released, and the dragged object can be dragged about with the mouse button up.
    I'm running JDK1.3.0 on NT4 with service pack 6.
    Anyone know if this is a bug ?
    Paul Sandie

    It might be a bug...it's very hard to say given the information you gave....But a brief search on the bug parade gave this as a likely suspect:
    http://developer.java.sun.com/developer/bugParade/bugs/4200168.html
    Not too sure it's related to your case, though.
    HTH,
    Fredrik

  • How to paint drugging object

    Hi everyone!
    I have such a problem - i have to draw dragging object/jbjects (JLabels) on JPanel. I tried to use custom cursor but it can be 32x32 maximum size. I guess I must draw dragging mounually using Graphics of JPanel, but:
    1. How to call repaint method during dragging?
    2. How to paint several times in a second avoiding blinking of whole scene?

    Crosswinder wrote:
    I have such a problem - i have to draw dragging object/jbjects (JLabels) on JPanel. I tried to use custom cursor but it can be 32x32 maximum size. I guess I must draw dragging mounually using Graphics of JPanel, but:
    1. How to call repaint method during dragging?
    2. How to paint several times in a second avoiding blinking of whole scene?If I understand you correctly, you have a JLabel on a JPanel and you want to click on it and drag it somewhere else, much like you would see in a chess application where a chess piece is on a chessboard and then dragged to another position. If this is what you want to do, then one solution is to use a JLayeredPane, to have your JLabel with its ImageIcon initially held in the JLayeredPane's default layer (JLayeredPane.DEFAULT_LAYER). Then when the JLabel is clicked on, raise it to the JLayeredPane.DRAG_LAYER, and as the mouse moves (from within a MouseAdapter object), move the JLabel as well. An example of this can be found here: [questions-about-events-differents-layers: Fubarable's post 10|http://www.java-forums.org/awt-swing/30640-questions-about-events-differents-layers.html#post132204]
    Much luck.

  • 1.4 dnd question

    I am looking to be able to drag from a JList onto a container (i.e. JPanel) and have it create a JLabel. I would also like to be able to drag onto existing JLabels in the container and have it create borders around the JLabels. I guess I'm looking to implement context sensitive dragging...
    Can someone point me towards a reference that will help me understand how to implemement this?
    thanks.

    Thank you for your try.
    Your code doesn't solve my problem.
    Assume that the drag source is the WindowsExplorer. The user picks a file and drag it over a Java component. If it isn't possible to get the DragSourceContext, there is no way to read from the dragged file while dragging. So the component cannot analize the contents of the file and is not able to verify that the user is able to drop it.
    Think about a XML structure display.
    The user drags an XML file form WindowsExplorer to the display. Now the display must check the filename, the file extension or the file contents to check that it is able to read the XML file.
    I think it is to late when the display sends a message after drop to the user that the file isn't a XML file.
    Best regards
    Andy

  • Drag a JLabel, drop in a JList

    I'm trying to implement a drop-and-drag feature in my program.
    I have a class Book, which extends a JLabel with and ID field (as a string) and a get and set method for the ID in it, as well as a toString method which returns the ID.
    I need to drag the label over a JList and add the label's ID to the list, directly below the selected index over which the mouse dropped.
    So far i have tried to override the transferhandler with example String and List handlers i found on the site (at http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/ListTransferHandler.java and http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/StringTransferHandler.java ) however, it seems the problem keeps getting bigger the more i try to edit them.
    Also, i have tried to implement Serializable and Transferable Book's, but I'm not entirely familiar with how to use the dataflavors, so that could also be causing the problem.
    I have tried a few possible scenarios with the transfer handler and so far this is getting me the most results:
    public class dragtest extends JPanel {
    public dragtest() {
    super(new GridLayout(3,1));
    add(createArea());
    add(createList());
    add(createBookcase(17));
    private JPanel createList() {
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("List one");
    listModel.addElement("List two");
    listModel.addElement("List three");
    JList list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    JScrollPane scrollPane = new JScrollPane(list);
    scrollPane.setPreferredSize(new Dimension(400,100));
    // do not allow list items to be dragged
    list.setDragEnabled(false);
    // list.setDropTarget();
    // DropTarget dt = new DropTarget();
    // list.setDropTarget(dt);
    list.setTransferHandler(new ListTransferHandler());
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createTitledBorder("List"));
    return panel;
    private JPanel createBookcase(int amount) {
    JPanel bookCase = new JPanel();
    int X1 = 30; // height from top
    int X2 = 20; // height to bottom
    int Y1 = 20; // distance from sides
    int Y2 = 10; // distance between images
    int Z1 = 60; // width of image
    int Z2 = 80; // height of image
    int numLabelsInCol = 5;
    int numDone = 0;
    int x = 0;
    for (int y = 0; y < numLabelsInCol; y++) {
    if (numDone < amount) {
    Book lbl = new Book(numDone, "address");
    lbl.setBounds( (Y1 + y * (Z1 + Y2)), (X1 + x * (Z2 + X2 + X1)), Z1, Z2);
    bookCase.add(lbl);
    String text = lbl.ID;
    lbl.setText(text);
    numDone++;
    lbl.setTransferHandler(new TransferHandler("text"));
    MouseListener listener = new DragMouseAdapter();
    lbl.addMouseListener(listener);
    bookCase.setPreferredSize(new Dimension(400, 100));
    return bookCase;
    private class DragMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) {
    JComponent c = (JComponent) e.getSource();
    TransferHandler handler = c.getTransferHandler();
    handler.exportAsDrag(c, e, TransferHandler.COPY);
    I realise it might be a little unconventional, the way i implement the transfer handler, but this actually prints out the ID on a JTextArea, however a list does not even react when i drag or drop the label over it. It does not even show a shaded area under which the mouse is.
    I have tried a multitude of examples but none of them have dealt with this. The only one which deals with JLabels dropped on a JList does not care for the order, however my program focuses on it.
    Please could anyone help?

    1) Swing related questions should be posted in the Swing forum
    2) When you poste code use the "code" formatting tags so the code retains its original formatting
    Using the ExtendedDnDDemo, from the Swing tutorial you referenced above, as the test program I created the following method:
        private JPanel createLabel() {
             JLabel label = new JLabel("Dnd Label");
            label.setTransferHandler(new LabelTransferHandler());
            label.addMouseListener( new MouseAdapter()
                 public void mousePressed(MouseEvent e)
                     JComponent c = (JComponent)e.getSource();
                     TransferHandler handler = c.getTransferHandler();
                     handler.exportAsDrag(c, e, TransferHandler.COPY);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(label, BorderLayout.CENTER);
            panel.setBorder(BorderFactory.createTitledBorder("Label"));
            return panel;
        }And the following class:
    * LabelTransferHandler.java is used by the 1.4
    * ExtendedDnDDemo.java example.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    public class LabelTransferHandler extends StringTransferHandler {
        // Get the text for export.
        protected String exportString(JComponent c) {
            JLabel label = (JLabel)c;
            return label.getText();
        //Take the incoming string and set the text of the label
        protected void importString(JComponent c, String str) {
            JLabel label = (JLabel)c;
            label.setText(str);
        protected void cleanup(JComponent c, boolean remove) {
    }

  • Java Drag and Drop from JMenu to JLabel

    Hello Fellow Coders,
    I am working on quite a large project right now. What I am trying to do is the following:
    1. When a user clicks on a custom button (extends JLabel) a context Menu opens. (works already)
    2. Now the user must be able to drag text from that menu onto another custom button.
    3. When the user drops that text on the target, the copied text should be written into a sql database.
    How can I accomplish that?
    I can't seem to find the right starting point.
    Best Regards
    Oliver

    Hey folks,
    after half a day of research and API studies I figured it out now. Since JMenu doesn't offer DnD Support AFAIK I had to switch to a JLIST.
    Then I had to write my own Transfer Handler / extend the Default Transfer Handler and now it works great. I'll post a few code snippets, maybe this is useful to somebody. I havn't tested it through yet, so it's definitly not bug free.
    This is the String TransferHandler from Sun (saved some work :) )
    public abstract class StringTransferHandler extends TransferHandler {
        protected abstract String exportString(JComponent c);
        protected abstract void importString(JComponent c, String str);
        protected abstract void cleanup(JComponent c, boolean remove);
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection(exportString(c));
        public int getSourceActions(JComponent c) {
            return MOVE;
        public boolean importData(JComponent c, Transferable t) {
            if (canImport(c, t.getTransferDataFlavors())) {
                try {
                    String str = (String)t.getTransferData(DataFlavor.stringFlavor);
                    importString(c, str);
                    return true;
                } catch (UnsupportedFlavorException ufe) {
                } catch (IOException ioe) {
            return false;
        protected void exportDone(JComponent c, Transferable data, int action) {
            cleanup(c, action == MOVE);
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (DataFlavor.stringFlavor.equals(flavors)) {
    return true;
    return false;
    My Custom transfer handler, you'll get the idea i supposepublic class BookingTransferHandler extends StringTransferHandler {
    protected void importString(JComponent c, String str) {
         KasseDB.splitTable(str, c.getName());
    You'll have to implement a few more methods, i didn't post. If you need more code just contact me, I'll send you a working example.
    KasseDB.splitTable() is the workhorse that does the Database work.
    Don't forget to set the TransferHandler on your targets with target.setTransferHandler(new BookingTransferhandler()) as in my case.
    Best Regards
    Oliver                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Dragging a jlabel

    hi
    i have JPanel wherin i have n labels
    i need to drag one of the labels to someother location on the panel
    im using java.awt.dnd....and i need to use it cos mouse dragged event is not working properly
    drag n drop action should be Move
    ie when i drag a label it should be removed from the current location n placed in the new location
    and i should have the shadow the label following the drag
    three labels r all different
    i can have as many labels as i want......
    any code references should help
    thanks
    thanks

    any guesses

  • 'Show JInternalFrame Contents While Dragging'

    hi,
    I have a question I have an application that has internal frames, Basically it is a MDI Application. I am using JDK 1.2.2 and windows 2000. The question is that when you go to the desktop right click properties and in Effects tab you uncheck the 'Show Window Contents While Dragging' checkBox. Now when I run my application and my parent window that is a frame pops up, if I drag the window i.e. my parent frame it doesn't dragg the contents onlt thw windows border is dragged, means it doesn't repaints that is fine. But when I try to drag one of the internal frame it shows me the contents inside the internalFrame being dragged too and I don't want to see these contents while internal frame is being dragged. So how can I make my application not to show the contents inside the JInternalFrames not to be shown while dragging the JInternalFrame. Any help is really appreciated.
    for an example I have added a code example to see the effect that I got from the forums just for an example to show. If you have unchecked the option 'Show Window Contents While Dragging' in Effects tab when you go to the desktop right click properties and the Effects Tab or in the controlPanel dblClick Display and go to Effects tab and uncheck this checkBox. Now run this example and see when you drag the main window contents inside it including JInternalFrame doesn't get dragged just the boundry of the dragging frame is shown. Now if you try to drag the JInternalFrame. Contents inside that are dragged too. And I don't want this behavior. I don't want to see the contents.
    /*************** MDITest ************/
    import javax.swing.*;
    * An application that displays a frame that
    * contains internal frames in an MDI type
    * interface.
    * @author Mike Foley
    public class MDITest extends Object {
    * Application entry point.
    * Create the frame, and display it.
    * @param args Command line parameter. Not used.
    public static void main( String args[] ) {
    try {
    UIManager.setLookAndFeel(
    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
    } catch( Exception ex ) {
    System.err.println( "Exception: " +
    ex.getLocalizedMessage() );
    JFrame frame = new MDIFrame( "MDI Test" );
    frame.pack();
    frame.setVisible( true );
    } // main
    } // MDITest
    /*********** MDIFrame.java ************/
    import java.awt.*;
    import java.awt.event.*;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    * A top-level frame. The frame configures itself
    * with a JDesktopPane in its content pane.
    * @author Mike Foley
    public class MDIFrame extends JFrame implements Serializable {
    * The desktop pane in our content pane.
    private JDesktopPane desktopPane;
    * MDIFrame, null constructor.
    public MDIFrame() {
    this( null );
    * MDIFrame, constructor.
    * @param title The title for the frame.
    public MDIFrame( String title ) {
    super( title );
    * Customize the frame for our application.
    protected void frameInit() {
    // Let the super create the panes.
    super.frameInit();
    JMenuBar menuBar = createMenu();
    setJMenuBar( menuBar );
    JToolBar toolBar = createToolBar();
    Container content = getContentPane();
    content.add( toolBar, BorderLayout.NORTH );
    desktopPane = new JDesktopPane();
    desktopPane.setPreferredSize( new Dimension( 400, 300 ) );
    content.add( desktopPane, BorderLayout.CENTER );
    } // frameInit
    * Create the menu for the frame.
    * <p>
    * @return The menu for the frame.
    protected JMenuBar createMenu() {
    JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu( "File" );
    file.setMnemonic( KeyEvent.VK_F );
    JMenuItem item;
    file.add( new NewInternalFrameAction() );
    // file.add( new ExitAction() );
    menuBar.add( file );
    return( menuBar );
    } // createMenuBar
    * Create the toolbar for this frame.
    * <p>
    * @return The newly created toolbar.
    protected JToolBar createToolBar() {
    final JToolBar toolBar = new JToolBar();
    toolBar.setFloatable( false );
    toolBar.add( new NewInternalFrameAction() );
    // toolBar.add( new ExitAction() );
    return( toolBar );
    * Create an internal frame.
    * A JLabel is added to its content pane for an example
    * of content in the internal frame. However, any
    * JComponent may be used for content.
    * <p>
    * @return The newly created internal frame.
    public JInternalFrame createInternalFrame() {
    JInternalFrame internalFrame =
    new JInternalFrame( "Internal JLabel" );
    internalFrame.getContentPane().add(
    new JLabel( "Internal Frame Content" ) );
    internalFrame.setResizable( true );
    internalFrame.setClosable( true );
    internalFrame.setIconifiable( true );
    internalFrame.setMaximizable( true );
    internalFrame.pack();
    return( internalFrame );
    * An Action that creates a new internal frame and
    * adds it to this frame's desktop pane.
    public class NewInternalFrameAction extends AbstractAction {
    * NewInternalFrameAction, constructor.
    * Set the name and icon for this action.
    public NewInternalFrameAction() {
    super( "New", new ImageIcon( "new.gif" ) );
    * Perform the action, create an internal frame and
    * add it to the desktop pane.
    * <p>
    * @param e The event causing us to be called.
    public void actionPerformed( ActionEvent e ) {
    JInternalFrame internalFrame = createInternalFrame();
    desktopPane.add( internalFrame,
    JLayeredPane.DEFAULT_LAYER );
    } // NewInternalFrameAction
    } // MDIFrame
    I'll really appreciate for any help.
    Thank you

    try this:
    JDesktopPane desktopPane = new JDesktopPane();
    desktopPane.putClientProperty("JDesktopPane.dragMode", "outline");Both parameters passed to 'putClientProperty' must be strings.
    Hope this helps
    Riz

  • How to drag and drop a file with its Systemfile icon to a Jtext area

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

  • Dragging only a portion of data from a cell?

    I'm working on a scheduling program (using Java/Swing) that simply has several tables that I drag and drop information pulled from a database. In one table I have it set up so that the user can drag multiple data (people�s names) into a single cell (just concatenate the new name with the existing names). However, I now need the ability to drag a specific name outside the table (to delete it). Since I treat the contents of the whole cell as one big string, I'm stumped as what to do next. I'm new to Java, but have been reading about custom renderers and was wondering if it would be possible to write one that would work in my situation. I'm also open to any other ways that would make specific selection possible. So far this is what has been suggested:
    - find a method of detecting which name is underneath the mouse when a cell is clicked on. You'd need a custom table model such that every cell returns some collection of custom objects representing each name.
    - write a cell renderer so that you can highlight specific names in a cell when the mouse is clicked on one
    - add your drag and drop code using the above two features
    Any help would be greatly appreciated.

    I'm working on a scheduling program (using
    Java/Swing) that simply has several tables that I
    drag and drop information pulled from a database. In
    one table I have it set up so that the user can drag
    multiple data (people�s names) into a single cell
    (just concatenate the new name with the existing
    names). However, I now need the ability to drag a
    specific name outside the table (to delete it). Since
    I treat the contents of the whole cell as one big
    string, I'm stumped as what to do next. I'm new to
    Java, but have been reading about custom renderers
    and was wondering if it would be possible to write
    one that would work in my situation. I'm also open to
    any other ways that would make specific selection
    possible. So far this is what has been suggested:
    - find a method of detecting which name is underneath
    the mouse when a cell is clicked on. You'd need a
    custom table model such that every cell returns some
    collection of custom objects representing each name.
    - write a cell renderer so that you can highlight
    specific names in a cell when the mouse is clicked on
    one
    - add your drag and drop code using the above two
    features
    Any help would be greatly appreciated.I made a cell renderer that is a JPanel subclass that stores JLabels (each representing a name) and the labels will be laid out using a FlowLayout in the panel - that way the names "wrap" in the table cell. Now I need to create a method in my JPanel subclass to return which component is at (x,y), and highlight that component in my renderer getCellRenderComponent() method.
    Any ideas how to implement this method?

  • Re-order components in JPanel using Drag and Drop

    Hi,
    I have a JPanel that contains some more JPanels (the Layout is GridBagLayout - one column, each row - 1 JPanel). I would like to drag one JPanel (1) and after dropping it on some other JPanel (2), the (1) should be inserted at (2)'s position.
    I really can't get the idea from sun's tutorials :(

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class DragTest extends JPanel
        public DragTest()
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weighty = 1.0;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            for(int j = 0; j < 4; j++)
                JPanel panel = new JPanel(new BorderLayout());
                panel.setBorder(BorderFactory.createEtchedBorder());
                panel.add(new JLabel("panel " + (j+1), JLabel.CENTER));
                add(panel, gbc);
        public static void main(String[] args)
            DragTest test = new DragTest();
            DragListener listener = new DragListener(test);
            test.addMouseListener(listener);
            test.addMouseMotionListener(listener);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class DragListener extends MouseInputAdapter
        DragTest dragTest;
        Component selectedComponent;
        GridBagConstraints constraints;
        Point start;
        boolean dragging;
        final int MIN_DRAG_DISTANCE = 5;
        public DragListener(DragTest dt)
            dragTest = dt;
            dragging = false;
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            Component[] c = dragTest.getComponents();
            for(int j = 0; j < c.length; j++)
                Rectangle r = c[j].getBounds();
                if(r.contains(p))
                    selectedComponent = c[j];
                    start = p;
                    dragging = true;
                    break;
        public void mouseReleased(MouseEvent e)
            if(dragging)  // no component has been removed
                dragging = false;
                return;
            Point p = e.getPoint();
            if(!dragTest.getBounds().contains(p))  // out of bounds
                // failed drop - add back at index = 0
                dragTest.add(selectedComponent, constraints, 0);
                dragTest.revalidate();
                return;
            Component comp = dragTest.getComponentAt(p);
            int index;
            if(comp == dragTest)
                index = getDropIndex(dragTest, p);
            else  // over a child component
                Rectangle r = comp.getBounds();
                index = getComponentIndex(dragTest, comp);
                if(p.y - r.y > (r.y + r.height) - p.y)
                    index += 1;
            dragTest.add(selectedComponent, constraints, index);
            dragTest.revalidate();
        private int getDropIndex(Container parent, Point p)
            Component[] c = parent.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j].getY() > p.y)
                    return j;
            return -1;
        private int getComponentIndex(Container parent, Component target)
            Component[] c = parent.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] == target)
                    return j;
            return -1;
        public void mouseDragged(MouseEvent e)
            if(dragging)
                if(e.getPoint().distance(start) > MIN_DRAG_DISTANCE)
                    // save constraints for the drop
                    GridBagLayout layout = (GridBagLayout)dragTest.getLayout();
                    constraints = layout.getConstraints(selectedComponent);
                    dragTest.remove(selectedComponent);
                    dragging = false;
                    dragTest.revalidate();
    }

  • Drag and Drop Export Done is called too soon...

    Hi,
    I am trying to drag and drop a JLabel from a JPanel into another JPanel. I am no where near to figuring it out, but just for starters I notice that the exportDone() method is called in my custom TransferHandler immediately when the drag begins. Even stranger, createTransferable() is never called. (I am comparing my code to the DragPictureDemo that I found online). The question is, why is exportDone called immediately? Code below. Thanks. (BTW, any other suggestions about what I'm trying to do would be appreciated. I'm not confident in the direction I'm taking here... have yet to understand the Swing DnD mechanism...)
    From DragPictureDemo, I notice that createTransferable and exportAsDrag are called immediately upon drag, and exportDone is called at the drop.
    Here is my code: First, the main class Testola.java:
    * Created on Oct 31, 2007
    * Copyright 2006 Michael Anthony Schwager.
    * This software comes without warranty or applicability for any purpose.
    * Rights granted for any use.
    package testola;
    import javax.swing.*;
    import java.awt.*;
    public class Testola implements Runnable {
          * @param args
         public void run() {
              /*char[] stdout_arr={};
              String blah;
              blah=new String(stdout_arr, 0, 0);
              StringBuffer buf=null;
              System.out.println("Hello world." + " wow" + null + "<-null");*/
              // --------- FRAME ---------
              JFrame frame=new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(30,30,500,400);
            JDesktopPane dtp=new JDesktopPane();
            frame.getContentPane().add(dtp);
            // First Internal Frame; false means no close box.
            JInternalFrame jif=new JInternalFrame("One", true, false, true, true     ); //jif.setBounds(0,0,100,50);
            DnDJPanel contentPanel=new DnDJPanel(); contentPanel.setBackground(new Color(255,255,180));
            contentPanel.setLayout(null);
            // Then JLabels, first 1
            JLabel test1=new JLabel("test1!"); test1.setBounds(0, 0, 50, 20);
            test1.setBorder(BorderFactory.createLineBorder(Color.RED));
            //test1.setTransferHandler(new JComponentTransferHandler());
            contentPanel.add(test1);
            // 2
            JLabel test2=new JLabel("test2!"); test2.setBounds(10, 30, 50, 20);
            test2.setBorder(BorderFactory.createLineBorder(Color.GREEN));
            //test1.setTransferHandler(new JComponentTransferHandler());
            contentPanel.add(test2);
            // Finalize Frame
            contentPanel.setBounds(0,0,250,140);
            contentPanel.setTransferHandler(new JComponentTransferHandler());
            contentPanel.setVisible(true);
            jif.setBounds(10,10,250,140);
            jif.setContentPane(contentPanel);
            jif.setVisible(true);
            // Second Internal Frame
            DnDJInternalFrame jif2=new DnDJInternalFrame("Two", true, false, true, true     );
            // JPanel and jtextfield to add to Frame2
            // Finalize Frame2
            jif2.getContentPane().setLayout(null);
            jif2.setBounds(120,150,200,155);
            jif2.setVisible(true);
            dtp.add(jif);
            dtp.add(jif2);
            try {jif.setIcon(false);} catch (Exception e) {System.err.println("setIcon exception");}
              frame.setVisible(true);
         public static void main(String[] args) {
              Testola testola=new Testola();
              try {EventQueue.invokeAndWait(testola);} catch (Exception e) { System.out.println(e);};
              //testola.run();
              System.out.println("Exit");
    }Now, my JComponentTransferHandler.java:
    * Created on Apr 12, 2008
    * Copyright 2006 Michael Anthony Schwager.
    * This file is part of testola.
    * testola is free software; you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation; either version 2 of the License, or
    * (at your option) any later version.
    * testola is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    *  (You should have received a copy of the GNU General Public License
    *  along with testola; if not, write to the Free Software
    *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    package testola;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.event.InputEvent;
    import javax.swing.JComponent;
    import javax.swing.TransferHandler;
    public class JComponentTransferHandler extends TransferHandler {
         public JComponentTransferHandler() {
              super();
         public JComponentTransferHandler(String property) {
              super(property);
         public void exportDone(JComponent source, Transferable data, int action) {
              super.exportDone(source, data, action);
              System.out.println("Export is done!");
         public boolean importData(JComponent comp, Transferable t) {
              boolean res;
              res=super.importData(comp, t);
              System.out.println("Import is done! " + res);
              return res;
         public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
              boolean res;
              res=super.canImport(comp, transferFlavors);
              System.out.println("Can import: " + res);
              return res;
        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
             super.exportAsDrag(comp, e, action);
             System.out.println("Export as drag: " + comp.getClass().getName());
        protected Transferable createTransferable(JComponent c) {
            System.out.println("createTransferable, arg: " + c.getClass().getName());
             Transferable t=super.createTransferable(c);
            return t;
    }Edited by: Hushpuppy on Apr 13, 2008 7:59 PM
    Edited by: Hushpuppy on Apr 13, 2008 8:02 PM
    Edited by: Hushpuppy on Apr 13, 2008 8:13 PM

    No idea whether this will be helpful, but exportDone() is not called immediately if you remove the call to super.exportAsDrag.
    db
    edit Since your earlier post, I've been trying to teach myself Swing DnD, but am finding the documentation confusing and the tutorials primitive... I'd reached a conclusion, which has every chance of being wrong, that I should call createTransferable from exportAsDrag. FWIW these are the methods as of now -- nothing works :-(   @Override
       public void exportAsDrag(JComponent comp, InputEvent e, int action) {
          // count is a instance field to monitor repeated calls
          System.out.println(count + ". " + "exportAsDrag"); count++;
          //super.exportAsDrag(comp, e, action);
          // dragSource is a instance field of type Container
          dragSource = comp.getParent();
          createTransferable(comp);
       @Override
       protected Transferable createTransferable(JComponent child) {
          System.out.println(count + ". " + "createTransferable"); count++;
          // ComponentHandler implements Transferable
          Transferable t = new ComponentHandler(child);
          return t;
       }The commented line is from testing a possible cause of your problem, since my code never gets as far as exportDone() :-(
    Edited by: Darryl.Burke

  • Drag & Drop of a file not working in Ubuntu & other linux

    Hi All,
    I am working on a project,in which it has the requirement of dragging the files
    from a JList present inside a JFrame to the desktop.
    First I tried to get a solution using dnd API but could not. Then i googled and i got an application which is
    working perfectly in both Windows and MAC Operating systems, after I made few minor changes to suit my requirements.
    Below is the URL of that application:
    http://stackoverflow.com/questions/1204580/swing-application-drag-drop-to-the-desktop-folder
    The problem is the same application when I executed on Ubuntu, its not working at all. I tried all available options but could not trace out the exact reason.
    Can anybody help me to overcome this issue?
    Thanks in advance

    Hi,
    With the information you provided and through some information found on google i coded an application. This application is able to do the drag and drop of an item from the Desktop to Java application on Linux Platform, but i am unble to do the viceversa by this application.
    I am including the application and the URL of the information i got.
    [URL Of Information Found|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4899516]
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.DefaultListModel;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.TransferHandler;
    import javax.swing.WindowConstants;
    public class DnDFrame extends JFrame implements DropTargetListener {
         private DefaultListModel listModel = new DefaultListModel();
         private DropTarget dropTarget;
         private JLabel jLabel1;
         private JScrollPane jScrollPane1;
         private JList list;
         List<File> files;
         /** Creates new form DnDFrame */
         public DnDFrame() {
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              initComponents();
              dropTarget = new DropTarget(list, this);
              list.setModel(listModel);
              list.setDragEnabled(true);
              list.setTransferHandler(new FileTransferHandler());
         @SuppressWarnings("unchecked")
         private void initComponents() {
              GridBagConstraints gridBagConstraints;
              jLabel1 = new JLabel();
              jScrollPane1 = new JScrollPane();
              list = new JList();
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              getContentPane().setLayout(new GridBagLayout());
              jLabel1.setText("Files:");
              gridBagConstraints = new GridBagConstraints();
              gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
              gridBagConstraints.anchor = GridBagConstraints.WEST;
              getContentPane().add(jLabel1, gridBagConstraints);
              jScrollPane1.setViewportView(list);
              gridBagConstraints = new GridBagConstraints();
              gridBagConstraints.gridwidth = GridBagConstraints.REMAINDER;
              gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
              getContentPane().add(jScrollPane1, gridBagConstraints);
              pack();
         public void dragEnter(DropTargetDragEvent arg0) {
         public void dragOver(DropTargetDragEvent arg0) {
         public void dropActionChanged(DropTargetDragEvent arg0) {
         public void dragExit(DropTargetEvent arg0) {
         public void drop(DropTargetDropEvent evt) {
              System.out.println(evt);
              int action = evt.getDropAction();
              evt.acceptDrop(action);
              try {
                   Transferable data = evt.getTransferable();
                   DataFlavor uriListFlavor = null;
                   try {
                        uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
                   } catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                   System.out.println("data.isDataFlavorSupported(DataFlavor.javaFileListFlavor: " +
                             data.isDataFlavorSupported(DataFlavor.javaFileListFlavor) );
                   if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
                        for (File file : files) {
                             listModel.addElement(file);
                   }else if (data.isDataFlavorSupported(uriListFlavor)) {
                        String data1 = (String)data.getTransferData(uriListFlavor);
                        files = (List<File>) textURIListToFileList(data1);
                        for (File file : files) {
                             listModel.addElement(file);
                        System.out.println(textURIListToFileList(data1));
              } catch (UnsupportedFlavorException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
              } finally {
                   evt.dropComplete(true);
         private static java.util.List textURIListToFileList(String data) {
              java.util.List list = new java.util.ArrayList(1);
              for (java.util.StringTokenizer st = new java.util.StringTokenizer(data,"\r\n");
              st.hasMoreTokens();) {
                   String s = st.nextToken();
                   if (s.startsWith("#")) {
                        continue;
                   try {
                        java.net.URI uri = new java.net.URI(s);
                        java.io.File file = new java.io.File(uri);
                        list.add(file);
                   } catch (java.net.URISyntaxException e) {
                   } catch (IllegalArgumentException e) {
              return list;
         private class FileTransferHandler extends TransferHandler {
              @Override
              protected Transferable createTransferable(JComponent c) {
                   JList list = (JList) c;
                   List<File> files = new ArrayList<File>();
                   for (Object obj: list.getSelectedValues()) {
                        files.add((File)obj);
                   return new FileTransferable(files);
              @Override
              public int getSourceActions(JComponent c) {
                   return COPY;
         static {
              try {
                   uriListFlavor = new
                   DataFlavor("text/uri-list;class=java.lang.String");
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
         private class FileTransferable implements Transferable {
              private List<File> files;
              public FileTransferable(List<File> files) {
                   this.files = files;
              public DataFlavor[] getTransferDataFlavors() {
                   return new DataFlavor[]{DataFlavor.javaFileListFlavor,uriListFlavor};
              public boolean isDataFlavorSupported(DataFlavor flavor) {
                   if(flavor.equals(DataFlavor.javaFileListFlavor) || flavor.equals(uriListFlavor))
                        return true;
                   else
                        return false;
              public Object getTransferData(DataFlavor flavor) throws
              UnsupportedFlavorException, java.io.IOException {
                      if (isDataFlavorSupported(flavor) && flavor.equals(DataFlavor.javaFileListFlavor)) {
                        return files;
                   }else if (isDataFlavorSupported(flavor) && flavor.equals(uriListFlavor)) {
                        java.io.File file = new java.io.File("file.txt");
                        String data = file.toURI() + "\r\n";
                        return data;
                   }else {
                        throw new UnsupportedFlavorException(flavor);
         private static DataFlavor uriListFlavor;
         static {
              try {
                   uriListFlavor = new
                   DataFlavor("text/uri-list;class=java.lang.String");
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
         public static void dumpProperty(String name) {
              System.out.println(name + " \t" + System.getProperty(name) );
         public static void main(String[] args) {
              String[] props = {
                        "java.version",
                        "java.vm.version",
                        "java.vendor",
                        "os.name",
              "os.version"};
              for (String prop : props) {
                   dumpProperty(prop);
              Runnable r = new Runnable() {
                   public void run() {
                        DnDFrame f = new DnDFrame();
                        f.setVisible(true);
              SwingUtilities.invokeLater(r);
    }Please Suggest me in this.

Maybe you are looking for

  • How can I stop Acrobat from reordering files when importing files to create a PDF?

    To all those more knowledgable than I, I am converting a larger amount of tiff files into one PDF. The TIFF files are numbered 1-100. When I "add files" in the diaologe window they reorder because Acrobat does not look at the third number so then I h

  • Can a PDF of each web submission be sent to me when submitted

    We'd like an exact PDF of the form they filled out on the web sent to us so we can save it with their records as proof of orginal data submitted to us.  Possible?

  • Burning disk images on Disk Utility...

    How do I burn multiple Disk Images onto a single DVD that I can then use on a PC? I have several 3 CD application images, and I want to convert them to DVD, but I can't figure it out, and I have no clue how this can be done! thanks! (PS) I also have

  • Share to YouTube - uploading issues

    After messing around with this for the last 2 days... i've come to a few conclusions.. one is... there are some bugs that still need to be worked out with iMovie '08 and the Share to YouTube function. I made my first iMovie '08 project the other day,

  • Invitation script/Alert script

    I've been searching high and low for a answer and I haven't been able to find anything that helps me so hopefully someone here will be able to help. Here is the situation - My employer has me keep track of their appointments and I keep them on ical.