从浏览器拖动图像以放到JLabel上

时间:2012-01-07 11:31:38

标签: java swing browser drag-and-drop jlabel

我希望能够在JLabel被丢弃的情况下在JLabel上设置图像。一个网络浏览器。我的实施基于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;
}

对于DataFlavor.javaFileListFlavor部分,一切正常,但是使用DataFlavor.imageFlavour,生成的图像始终为null,并且在实例化ImageIcon时抛出NullPointerException。

有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:4)

您的代码似乎没问题。我使用以下代码对其进行了测试,并将图像从我的webbrowser(谷歌浏览器)拖放到JPanel上设置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;
      }
    };
  }
}

这是使用JDK1.6在我的Mac上测试的

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)

答案 1 :(得分:0)

使用Windows 7,java版“1.6.0_29”和Firefox 8.0.1,运行正常。 但是其他浏览器不起作用......

稍作修改:

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;
        }
    };
}

我从Firefox和DataFlavor []中删除了一个图像,可以看到这一行:     java.awt.datatransfer.DataFlavor中[mime类型=图像/ X-java的图像; representationclass = java.awt.Image中]

使用Chrome我看不到这一行:它不会返回正确的MIME类型以匹配DataFlavor.imageFlavor