Beginner
Beginner

Reputation: 171

Drag and Drop svg file in a canvas

I have created an editor, in which I display a canvas. I would like to allow DnD for svg files.

The fact is that I allow to drop files with this part of code :

int operations = DND.DROP_COPY | DND.DROP_MOVE;
Transfer[] types = new Transfer[]{FileTransfer.getInstance()};

DropTarget dt = new DropTarget(parent, operations);
    dt.setTransfer(types);
    dt.addDropListener(new DropTargetAdapter() {
    public void drop(DropTargetEvent event) {
    //ToDo
    }

But it allows any type of files, and I only want .svg files. How could I create a condition, which will check if the file dropped is a .svg file or not, and if it is, create a new canvas with the imported file ?

I would like to recover the path of the dropped file too, any idea of how I could do that ?

I don't really know how I could restrict the imported file to svg.

Upvotes: 0

Views: 406

Answers (1)

Baz
Baz

Reputation: 36894

Assuming that all your files have a valid .svg extension, check the file extension in the adapter and only use those files that have the right extension while ignoring files with other extensions.

Then do what you need to do with the files:

public static void main(String[] args)
{
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Stackoverflow");
    shell.setLayout(new FillLayout());

    Label label = new Label(shell, SWT.NONE);

    DropTarget target = new DropTarget(label, DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY);

    Transfer[] transfers = new Transfer[]{FileTransfer.getInstance()};

    target.setTransfer(transfers);
    target.addDropListener(new DropTargetAdapter()
    {
        public void drop(DropTargetEvent event)
        {
            if (event.data == null)
            {
                event.detail = DND.DROP_NONE;
                return;
            }

            String[] paths = (String[]) event.data;
            List<File> files = new ArrayList<>();

            for (String path : paths)
            {
                int index = path.lastIndexOf(".");
                if (index != -1)
                {
                    String extension = path.substring(index + 1);
                    if (Objects.equals(extension, "svg"))
                        files.add(new File(path));
                }
            }

            System.out.println(files);
        }
    });

    shell.pack();
    shell.open();
    shell.setSize(400, 300);

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

Upvotes: 2

Related Questions