Philippe
Philippe

Reputation: 2029

Drag image from browser to drop onto JLabel

I want to be able to set an image on a JLabel when it's being dropped from e.g. a web browser. I've based the implementation upon Drag-and-Drop Support for Images.

@Override
public boolean importData(JComponent comp, Transferable t) {
    if (comp instanceof JLabel) {
        JLabel label = (JLabel) comp;
        if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            try {
                image = (Image) t.getTransferData(DataFlavor.imageFlavor);
                ImageIcon icon = new ImageIcon(image);
                label.setIcon(icon);
                return true;
            } catch (Throwable th) {
                log.error("Failed to accept dropped image", th);
            }
        } else if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            try {
                @SuppressWarnings("unchecked")
                List<File> files = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
                if (files.size() == 1) {
                        ImageIcon icon = new ImageIcon(files.get(0).getAbsolutePath());
                        label.setIcon(icon);
                }
                return true;
            } catch (Throwable th) {
                log.error("Failed to accept dropped image", th);
            }
        }
    }
    return false;
}

For the DataFlavor.javaFileListFlavor part everything works fine but with DataFlavor.imageFlavour the resulting image is always null and a NullPointerException is being thrown when the ImageIcon is being instantiated.

Someone knows why this is happening?

Upvotes: 2

Views: 2238

Answers (2)

Jean-Luc
Jean-Luc

Reputation: 1

Using Windows Seven, java version "1.6.0_29", and Firefox 8.0.1, works fine. But with other browsers don't works...

with a minor change:

private static TransferHandler createTransferHandler() {
    return new TransferHandler() {
        @Override
        public boolean importData(JComponent comp,
                Transferable aTransferable) {
            DataFlavor[] transferData = aTransferable.getTransferDataFlavors();
            for(DataFlavor df:transferData){
                System.out.println(df.toString());
            }

            System.out.println("-----------------------------------");
            return true;
        }

        @Override
        public boolean canImport(JComponent comp,
                DataFlavor[] transferFlavors) {
            return true;
        }
    };
}

I drop an image from Firefox and in DataFlavor[] and can see this line : java.awt.datatransfer.DataFlavor[mimetype=image/x-java-image;representationclass=java.awt.Image]

With Chrome I can't see this line: it don't returns the correct MIME type to match with DataFlavor.imageFlavor

Upvotes: 0

Robin
Robin

Reputation: 36601

Your code seems to be just fine. I tested it with the following code, and drag-and-drop of an image from my webbrowser (Google Chrome) onto the JPanel sets the image in the JLabel.

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class DragAndDropTester {
  private static final JLabel TEST_LABEL = new JLabel( "TestLabel" );

  public static void main( String[] args ) {
    try {
      EventQueue.invokeAndWait( new Runnable() {
        public void run() {

          JFrame testFrame = new JFrame( "Test" );

          JPanel contents = new JPanel( new BorderLayout() );
          contents.add( TEST_LABEL, BorderLayout.CENTER );

          contents.setTransferHandler( createTransferHandler() );

          testFrame.getContentPane().add( contents );
          testFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          testFrame.setSize( 200, 200 );
          testFrame.setVisible( true );
        }
      } );
    } catch ( InterruptedException e ) {
    } catch ( InvocationTargetException e ) {
    }
  }

  private static TransferHandler createTransferHandler(){
    return new TransferHandler(  ){
      @Override
      public boolean importData( JComponent comp, Transferable aTransferable ) {
        try {
          Object transferData = aTransferable.getTransferData( DataFlavor.imageFlavor );
          TEST_LABEL.setIcon( new ImageIcon( ( Image ) transferData ) );
        } catch ( UnsupportedFlavorException e ) {
        } catch ( IOException e ) {
        }
        return true;
      }

      @Override
      public boolean canImport( JComponent comp, DataFlavor[] transferFlavors ) {
        return true;
      }
    };
  }
}

This was tested on my Mac using JDK1.6

java version "1.6.0_29"
Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-10M3527)
Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode)

Upvotes: 4

Related Questions