Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Java - Come utilizzare il Drag&Drop con un JTextField
Forum - Java - Come utilizzare il Drag&Drop con un JTextField

Avatar
iMO (Normal User)
Newbie


Messaggi: 5
Iscritto: 06/12/2012

Segnala al moderatore
Postato alle 17:48
Giovedì, 06/12/2012
Salve a tutti

io vorrei poter utilizzare il Drag&Drop in modo tale da poter trascinare una cartella all'interno di un JTextField e che all'interno di tale JTextField compaia il percorso della cartella. Ho provato a utilizzare il tutorial inerente al Drag&Drop pubblicato sul sito ma senza molto successo. Grazie in anticipo per ogni eventuale risposta.

iMO

PM Quote
Avatar
bububs (Normal User)
Expert


Messaggi: 253
Iscritto: 11/03/2010

Segnala al moderatore
Postato alle 12:39
Venerdì, 07/12/2012


bububs ha allegato un file: filedrop-1.1.zip (52529 bytes)
Clicca qui per scaricare il file
PM Quote
Avatar
iMO (Normal User)
Newbie


Messaggi: 5
Iscritto: 06/12/2012

Segnala al moderatore
Postato alle 12:31
Sabato, 08/12/2012
Grazie mille per le dritte! :k: Ho risolto così:
Codice sorgente - presumibilmente Java

  1. import java.awt.*;
  2. import java.awt.datatransfer.DataFlavor;
  3. import java.awt.datatransfer.Transferable;
  4. import java.awt.dnd.DnDConstants;
  5. import java.awt.dnd.DropTarget;
  6. import java.awt.dnd.DropTargetDragEvent;
  7. import java.awt.dnd.DropTargetDropEvent;
  8. import java.awt.dnd.DropTargetEvent;
  9. import java.awt.dnd.DropTargetListener;
  10. import java.awt.event.ActionEvent;
  11. import java.awt.event.ActionListener;
  12. import javax.swing.JFrame;
  13. import javax.swing.JPanel;
  14. import javax.swing.JTextField;
  15.  
  16.  
  17. /**
  18.  *
  19.  * @author Nicolò
  20.  */
  21. public class Frame extends JFrame implements DropTargetListener, ActionListener{
  22.    
  23.     private static final long serialVersionUID = 2634459465126041816L;
  24.     public JPanel jp;
  25.     public JTextField txt;
  26.     public DropTarget dt;
  27.    
  28.     //Costruttore
  29.     public Frame(){
  30.         super("iMusicOrganizer v3.0");
  31.         setLocationRelativeTo(null);
  32.         setBounds(0,0,1200,430);
  33.                        
  34.         jp = new JPanel();
  35.         txt = new JTextField("Path...");
  36.        
  37.         Dimension d = new Dimension(1000,20);
  38.         txt.setPreferredSize(d);
  39.        
  40.         jp.add(txt);
  41.         getContentPane().add(jp);
  42.        
  43.         dt = new DropTarget(txt, this);
  44.                
  45.         setVisible(true);
  46.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  47.     }
  48.  
  49.     @Override
  50.     public void dragEnter(DropTargetDragEvent dtde) {
  51.         System.out.println("Drag Init");
  52.     }
  53.  
  54.     @Override
  55.     public void dragOver(DropTargetDragEvent dtde) {
  56.         System.out.println("Drag Over");
  57.     }
  58.  
  59.     @Override
  60.     public void dropActionChanged(DropTargetDragEvent dtde) {
  61.         System.out.println("Drop Action Changed");
  62.     }
  63.  
  64.     @Override
  65.     public void dragExit(DropTargetEvent dte) {
  66.         System.out.println("Drag End");
  67.     }
  68.  
  69.     @Override
  70.     public void drop(DropTargetDropEvent dtde) {
  71.         try {
  72.             /* Ok, get the dropped object and try to figure out what it is */
  73.             Transferable tr = dtde.getTransferable();
  74.             DataFlavor[] flavors = tr.getTransferDataFlavors();
  75.             for (int i = 0; i < flavors.length; i++) {
  76.                 System.out.println("Possible flavor: " + flavors[i].getMimeType());
  77.                 /* Check for file lists specifically */
  78.                 if (flavors[i].isFlavorJavaFileListType()) {
  79.                     // Great!  Accept copy drops...
  80.                     dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
  81.                     /*ta.setText("Successful file list drop.\n\n");*/
  82.                     // And add the list of file names to our text area
  83.                     @SuppressWarnings("rawtypes")
  84.                     java.util.List list = (java.util.List)tr.getTransferData(flavors[i]);
  85.                     for (int j = 0; j < list.size(); j++) {
  86.                         txt.setText(list.get(j) + "\n");
  87.                     }
  88.                     // If we made it this far, everything worked.
  89.                     dtde.dropComplete(true);
  90.                     return;
  91.                 }
  92.                 // Ok, is it another Java object?
  93.                 else if (flavors[i].isFlavorSerializedObjectType()) {
  94.                     dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
  95.                     txt.setText("Successful text drop.\n\n");
  96.                     Object o = tr.getTransferData(flavors[i]);
  97.                     txt.setText("Object: " + o);
  98.                     dtde.dropComplete(true);
  99.                     return;
  100.                 }
  101.        
  102.             }
  103.             System.out.println("Drop failed: " + dtde);
  104.             dtde.rejectDrop();
  105.             } catch (Exception e) {
  106.                 e.printStackTrace();
  107.                 dtde.rejectDrop();
  108.               }
  109.    
  110.     }
  111.  
  112.     @Override
  113.     public void actionPerformed(ActionEvent e) {
  114.        
  115.         //txt.addKeyListener(null);
  116.         txt.setText("Path Correct!!");
  117.     }
  118.  
  119.    
  120. }



Il problema ora è che non mi funziona più la gestione dell'evento quando premo invio per cambiare testo all'interno del JTextField.

PM Quote
Avatar
bububs (Normal User)
Expert


Messaggi: 253
Iscritto: 11/03/2010

Segnala al moderatore
Postato alle 23:48
Domenica, 09/12/2012
non capisco. Spiegati meglio. Cosa vuoi che faccia al premere del tasto invio?

PM Quote
Avatar
iMO (Normal User)
Newbie


Messaggi: 5
Iscritto: 06/12/2012

Segnala al moderatore
Postato alle 9:31
Lunedì, 10/12/2012
Semplicemente vorrei che quando premo invio nel JTextField, all'interno di esso venga sostituita la stringa presente con un'altra stringa definita (ad es. "Ok!").

PM Quote
Avatar
bububs (Normal User)
Expert


Messaggi: 253
Iscritto: 11/03/2010

Segnala al moderatore
Postato alle 13:25
Lunedì, 10/12/2012
Ok, molto semplice. Basta aggiungere nel costruttore questa riga di codice:
Codice sorgente - presumibilmente Java

  1. txt.addKeyListener( (KeyListener) new AscoltatoreTastiera() );


e prima dell'ultima parentesi graffa, cioè quella che chiude la classe Frame, inserisci quest'altra riga:
Codice sorgente - presumibilmente Java

  1. public class AscoltatoreTastiera extends KeyAdapter{
  2.         @Override
  3.         public void keyPressed(KeyEvent e) {
  4.             if(e.getKeyCode() == KeyEvent.VK_ENTER)
  5.                 txt.setText("Path Correct!!");
  6.         }
  7.     }


Ed ecco fatto :)
Un consiglio: nell'implements della classe lascia solo quella riguardante il drag&drop, eliminando ovviamente gli eventi associati, come l'actionlistener

PM Quote
Avatar
iMO (Normal User)
Newbie


Messaggi: 5
Iscritto: 06/12/2012

Segnala al moderatore
Postato alle 14:28
Martedì, 11/12/2012
Grazie mille! Tutto perfetto e funzionante :k: un'altra curiosità: ma come mai non funziona in ubuntu il drag and drop? Come posso renderlo compatibile?

PM Quote
Avatar
bububs (Normal User)
Expert


Messaggi: 253
Iscritto: 11/03/2010

Segnala al moderatore
Postato alle 16:29
Martedì, 11/12/2012
Mi dispiace ma non saprei perchè faccio parte del gruppo dei Windowsiani :rofl:
(non ho mai programmato su altri OS... solo nella shell di linux :rofl: )

Ultima modifica effettuata da bububs il 11/12/2012 alle 16:30
PM Quote