Sebastian
Sebastian

Reputation: 1912

Drag&Drop Images from a folder to a JTextPane

I want to implement a JTextPane to edit text, using images I drag and drop from my system into the JTextPane. I tried to implement it by using JTextPane as superclass and DropTargetListener as Interface. But when i'm trying to read my InputStream I get a NullPointerException. Please help.

import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JTextPane;

public class JTextTest extends JTextPane implements DropTargetListener {

private static final long serialVersionUID = 1L;

public JTextTest() {
    new DropTarget(this, this);
    this.setDragEnabled(true);
}

@Override
public void dragEnter(DropTargetDragEvent arg0) {
}

@Override
public void dragExit(DropTargetEvent arg0) {
}

@Override
public void dragOver(DropTargetDragEvent arg0) {
}

@Override
public void drop(DropTargetDropEvent dropTargetDropEvent) {
    System.out.println("Drop event");
    Transferable transferable = dropTargetDropEvent.getTransferable();
    for (DataFlavor d : transferable.getTransferDataFlavors()) {
        if (d.isRepresentationClassInputStream()) {
            dropTargetDropEvent
                    .acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            try {
                InputStream is = new BufferedInputStream(
                        (InputStream) transferable.getTransferData(d));

                ImageIcon image = new ImageIcon(ImageIO.read(is));
                this.insertIcon(image);
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } 

        } else {
            dropTargetDropEvent.rejectDrop();
        }
    }
    dropTargetDropEvent.getDropTargetContext().dropComplete(true);
}

@Override
public void dropActionChanged(DropTargetDragEvent arg0) {
}
}

Upvotes: 1

Views: 649

Answers (1)

COD3BOY
COD3BOY

Reputation: 12112

Try it with this snippet,

ImageIcon image = new ImageIcon(ImageIO.read(createImageInputStream(is)));

The ImageIO.read() expects a File ,ImageInputStream ,InputStream or URL and note that while dealing with images,most of the NullPointerException is thrown when there is a problem (more specifically reading the image returns null) with the image, image source or reading from that source.

Upvotes: 1

Related Questions