Drag n' drop externe

Résolu
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009 - 23 mai 2007 à 01:11
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009 - 23 mai 2007 à 22:37
Bonsoir à tous,
Je cherche une methode me permetant via un drag n' drop de recupérer l'adresse complète du fichier que j'aurai dropé vers un composant swing.

mon problème est de ne pas savoir le faire depuis un objet exterieur à ma frame.
exemple :
je souhaite recupérer le nom et adresse du fichier c:\thomas.txt en fesant depuis celui ci un glissé déposé vers ma jlist.

D'apres mes recherche cela me s'emble impossible, mais vu que d'en d'autres langage cela est assez simple.

D'avance merci pour votre aide.

NasserTom

7 réponses

Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
23 mai 2007 à 21:17
Salut,

fais le plutot en C/C++ pas besoin de rajouter la couche .net en plus d'une jvm...
inspire toi de ce poste -> ICI  j'y donne un lien pour apprendre le JNI et également un code d'exemple (derniere page).

------------------------------------
"On n'est pas au resto : ici on ne fait pas dans les plats tout cuits ..."

OoWORAoO
3
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009
23 mai 2007 à 22:13
Re bonjour,

J'ai finalement trouvé (comme quoi j'avais pas sufisament cherché )

bon il me faudra un certain temps pour comprendre quel partie du code m'est utile pour faire le drag n'drop, mais j'ai testé ce code qui me permet effectivement de faire le drag n'drop depuis l'explorer windows. (je testerai sous linux).

Je poste le code qui je pense sera utile a pas mal de monde.
merci pour votre aide.

import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;


public class ListDemo extends JFrame
                      implements ListSelectionListener
{
    private DroppableList list;
    private JTextField fileName;


    public ListDemo()
    {
        super("ListDemo");


        //Create the list and put it in a scroll pane
        list = new DroppableList();
        DefaultListModel listModel = (DefaultListModel)list.getModel();
        list.setCellRenderer(new CustomCellRenderer());
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        JScrollPane listScrollPane = new JScrollPane(list);


        String dirName = new String("\");
        String filelist[] = new File(dirName).list();
       
        for (int i=0; i < filelist.length ; i++ )
        {
            String thisFileSt = dirName+filelist[i];
            File thisFile = new File(thisFileSt);
            if (thisFile.isDirectory())
                continue;
            try {
                listModel.addElement(makeNode(thisFile.getName(),
                                              thisFile.toURL().toString(),
                                              thisFile.getAbsolutePath()));
            } catch (java.net.MalformedURLException e){
            System.out.println("listModel.addElement: "+e.getMessage());
            }
        }




        fileName = new JTextField(50);
        /*
        String name = listModel.getElementAt(
                              list.getSelectedIndex()).toString();
        fileName.setText(name);
*/
        //Create a panel that uses FlowLayout (the default).
        JPanel buttonPane = new JPanel();
        buttonPane.add(fileName);


        Container contentPane = getContentPane();
        contentPane.add(listScrollPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.NORTH);
    }


    public void valueChanged(ListSelectionEvent e)
    {
        if (e.getValueIsAdjusting() == false)
        {
            fileName.setText("");
            if (list.getSelectedIndex() != -1)
            {
                String name = list.getSelectedValue().toString();
                fileName.setText(name);
            }
        }
    }


    private static Hashtable makeNode(String name,
        String url, String strPath)
    {
        Hashtable hashtable = new Hashtable();
        hashtable.put("name", name);
        hashtable.put("url", url);
        hashtable.put("path", strPath);
        return hashtable;
    }


    public class DroppableList extends JList
        implements DropTargetListener, DragSourceListener, DragGestureListener
    {
        DropTarget dropTarget = new DropTarget (this, this);
        DragSource dragSource = DragSource.getDefaultDragSource();


        public DroppableList()
        {
          dragSource.createDefaultDragGestureRecognizer(
              this, DnDConstants.ACTION_COPY_OR_MOVE, this);
          setModel(new DefaultListModel());
        }


        public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent){}
        public void dragEnter(DragSourceDragEvent DragSourceDragEvent){}
        public void dragExit(DragSourceEvent DragSourceEvent){}
        public void dragOver(DragSourceDragEvent DragSourceDragEvent){}
        public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent){}


        public void dragEnter (DropTargetDragEvent dropTargetDragEvent)
        {
          dropTargetDragEvent.acceptDrag (DnDConstants.ACTION_COPY_OR_MOVE);
        }


        public void dragExit (DropTargetEvent dropTargetEvent) {}
        public void dragOver (DropTargetDragEvent dropTargetDragEvent) {}
        public void dropActionChanged (DropTargetDragEvent dropTargetDragEvent){}


        public synchronized void drop (DropTargetDropEvent dropTargetDropEvent)
        {
            try
            {
                Transferable tr = dropTargetDropEvent.getTransferable();
                if (tr.isDataFlavorSupported (DataFlavor.javaFileListFlavor))
                {
                    dropTargetDropEvent.acceptDrop (
                        DnDConstants.ACTION_COPY_OR_MOVE);
                    java.util.List fileList = (java.util.List)
                        tr.getTransferData(DataFlavor.javaFileListFlavor);
                    Iterator iterator = fileList.iterator();
                    while (iterator.hasNext())
                    {
                      File file = (File)iterator.next();
                      Hashtable hashtable = new Hashtable();
                      hashtable.put("name",file.getName());
                      hashtable.put("url",file.toURL().toString());
                      hashtable.put("path",file.getAbsolutePath());
                      ((DefaultListModel)getModel()).addElement(hashtable);
                    }
                    dropTargetDropEvent.getDropTargetContext().dropComplete(true);
              } else {
                System.err.println ("Rejected");
                dropTargetDropEvent.rejectDrop();
              }
            } catch (IOException io) {
                io.printStackTrace();
                dropTargetDropEvent.rejectDrop();
            } catch (UnsupportedFlavorException ufe) {
                ufe.printStackTrace();
                dropTargetDropEvent.rejectDrop();
            }
        }


        public void dragGestureRecognized(DragGestureEvent dragGestureEvent)
        {
            if (getSelectedIndex() == -1)
                return;
            Object obj = getSelectedValue();
            if (obj == null) {
                // Nothing selected, nothing to drag
                System.out.println ("Nothing selected - beep");
                getToolkit().beep();
            } else {
                Hashtable table = (Hashtable)obj;
                FileSelection transferable =
                  new FileSelection(new File((String)table.get("path")));
                dragGestureEvent.startDrag(
                  DragSource.DefaultCopyDrop,
                  transferable,
                  this);
            }
        }
    }


    public class CustomCellRenderer implements ListCellRenderer
    {
        DefaultListCellRenderer listCellRenderer =
          new DefaultListCellRenderer();
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean selected, boolean hasFocus)
        {
            listCellRenderer.getListCellRendererComponent(
              list, value, index, selected, hasFocus);
            listCellRenderer.setText(getValueString(value));
            return listCellRenderer;
        }
        private String getValueString(Object value)
        {
            String returnString = "null";
            if (value != null) {
              if (value instanceof Hashtable) {
                Hashtable h = (Hashtable)value;
                String name = (String)h.get("name");
                String url = (String)h.get("url");                returnString name + "> " + url;
              } else {
                returnString = "X: " + value.toString();
              }
            }
            return returnString;
        }
    }


    public class FileSelection extends Vector implements Transferable
    {
        final static int FILE = 0;
        final static int STRING = 1;
        final static int PLAIN = 2;
        DataFlavor flavors[] = {DataFlavor.javaFileListFlavor,
                                DataFlavor.stringFlavor,
                                DataFlavor.plainTextFlavor};
        public FileSelection(File file)
        {
            addElement(file);
        }
        /* Returns the array of flavors in which it can provide the data. */
        public synchronized DataFlavor[] getTransferDataFlavors() {
     return flavors;
        }
        /* Returns whether the requested flavor is supported by this object. */
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            boolean b  = false;
            b |=flavor.equals(flavors[FILE]);
            b |= flavor.equals(flavors[STRING]);
            b |= flavor.equals(flavors[PLAIN]);
         return (b);
        }
        /**
         * If the data was requested in the "java.lang.String" flavor,
         * return the String representing the selection.
         */
        public synchronized Object getTransferData(DataFlavor flavor)
       throws UnsupportedFlavorException, IOException {
     if (flavor.equals(flavors[FILE])) {
         return this;
     } else if (flavor.equals(flavors[PLAIN])) {
         return new StringReader(((File)elementAt(0)).getAbsolutePath());
     } else if (flavor.equals(flavors[STRING])) {
         return((File)elementAt(0)).getAbsolutePath();
     } else {
         throw new UnsupportedFlavorException(flavor);
     }
        }
    }


    public static void main(String s[])
    {
        JFrame frame = new ListDemo();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);
    }
}

NasserTom
3
Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
23 mai 2007 à 09:22
Salut,

ba il te reste la solution native en trouvant une api java qui permet de le faire ou en la codant toi meme.

------------------------------------
"On n'est pas au resto : ici on ne fait pas dans les plats tout cuits ..."

OoWORAoO
0
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009
23 mai 2007 à 21:05
Bonjour Twinuts,
merci pour ta reponse.
sais tu comment puis-je trouver ce genre d'api (je n'ai rien trouvé avec google).
qu'entend tu par le coder moi meme ? car j'ai l'impression que quoi que je code java ne voix pas les evenements externe.

penses tu que si je fais une dll en vb.net je peux l'utiliser avec java ? si oui sais tu comment puis je faire appel au procedure de la dll?
je sais faire en vb mais rien à voir avec java.

D'avance merci

NasserTom
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009
23 mai 2007 à 21:35
re,
waouh, c'est hyper chaud !!
Je ne pense pas avoir encore le niveau pour ce genre de chose (je n'ai que 2 mois de java).
je vais continuer à chercher une api java qui permet de le faire.

en tout cas merci pour ton aide ainsi que la qualité des solutions que tu proposes.

NasserTom
0
Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
23 mai 2007 à 22:23
Salut,

bien le code, ça m'ôte le doute sur la fesabilitée en java... pour info j'ai testé le code après avoir changé le dir par défaut et ça fonctionne, je suis sous linux et kde.

------------------------------------
"On n'est pas au resto : ici on ne fait pas dans les plats tout cuits ..."

OoWORAoO
0
nassertom Messages postés 43 Date d'inscription lundi 7 mai 2007 Statut Membre Dernière intervention 19 août 2009
23 mai 2007 à 22:37
Merci pour l'info cool cela reste portable en plus 

moi je test pour inclure le code minimum necessaire pour alimenter la jlist de mon appli.

NasserTom
0
Rejoignez-nous