Results 1 to 5 of 5
  1. #1
    ysl530 is offline Member
    Join Date
    Aug 2007
    Posts
    2
    Rep Power
    0

    Default help with drag and drop on JList

    I bulid two JLists(list1, list2) in a JPanel, I want to drag a element A from list1 and drop it on a element B of list2, then a event will occur (like a dialog, rather than just add A into list2). Can anyone tell me how to implement this. I kown how to just drop element into list2 but I don't kown how to make the event ocurr like I said.
    Thanks a lot for any help.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    
    public class ListDnD {
        ReportingListTransferHandler arrayListHandler =
                             new ReportingListTransferHandler();
    
        private JPanel getContent() {
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(getListComponent("left"));
            panel.add(getListComponent("right"));
            return panel;
        }
    
        private JScrollPane getListComponent(String s) {
            DefaultListModel model = new DefaultListModel();
            for(int j = 0; j < 5; j++)
                model.addElement(s + " " + (j+1));
            JList list = new JList(model);
            list.setName(s);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.setTransferHandler(arrayListHandler);
            list.setDragEnabled(true);
            return new JScrollPane(list);
        }
    
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ListDnD().getContent());
            f.setSize(400,200);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    }
    This is the ArrayListTransferHandler class from the tutorial with modifications to demonstrate the dialog.
    Java Code:
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import javax.swing.*;
    
    public class ReportingListTransferHandler extends TransferHandler {
        DataFlavor localArrayListFlavor, serialArrayListFlavor;
        String localArrayListType = DataFlavor.javaJVMLocalObjectMimeType +
                                    ";class=java.util.ArrayList";
        JList source = null;
        int[] indices = null;
        int addIndex = -1; //Location where items were added
        int addCount = 0;  //Number of items added
    
        public ReportingListTransferHandler() {
            try {
                localArrayListFlavor = new DataFlavor(localArrayListType);
            } catch (ClassNotFoundException e) {
                System.out.println(
                 "ReportingListTransferHandler: unable to create data flavor");
            }
            serialArrayListFlavor = new DataFlavor(ArrayList.class,
                                                  "ArrayList");
        }
    
        public boolean importData(JComponent c, Transferable t) {
            JList target = null;
            ArrayList alist = null;
            if (!canImport(c, t.getTransferDataFlavors())) {
                return false;
            }
            try {
                target = (JList)c;
                if (hasLocalArrayListFlavor(t.getTransferDataFlavors())) {
                    alist = (ArrayList)t.getTransferData(localArrayListFlavor);
                } else if (hasSerialArrayListFlavor(t.getTransferDataFlavors())) {
                    alist = (ArrayList)t.getTransferData(serialArrayListFlavor);
                } else {
                    return false;
                }
            } catch (UnsupportedFlavorException ufe) {
                System.out.println("importData: unsupported data flavor");
                return false;
            } catch (IOException ioe) {
                System.out.println("importData: I/O exception");
                return false;
            }
    
            // If you want the dialog to appear only for drags from the
            // left list and drops on the right JList.
            if(target.getName().equals("right") && target != source) {
                String message = "Do you want to drop here?";
                int retVal = JOptionPane.showConfirmDialog(target, message, "Confirm",
                                                           JOptionPane.YES_NO_OPTION,
                                                           JOptionPane.QUESTION_MESSAGE);
                System.out.println("retVal = " + retVal);
                if(retVal == JOptionPane.NO_OPTION || retVal == JOptionPane.CLOSED_OPTION)
                    return false;
            }
    
            //At this point we use the same code to retrieve the data
            //locally or serially.
    
            //We'll drop at the current selected index.
            int index = target.getSelectedIndex();
    
            //Prevent the user from dropping data back on itself.
            //For example, if the user is moving items #4,#5,#6 and #7 and
            //attempts to insert the items after item #5, this would
            //be problematic when removing the original items.
            //This is interpreted as dropping the same data on itself
            //and has no effect.
            if (source.equals(target)) {
                if (indices != null && index >= indices[0] - 1 &&
                      index <= indices[indices.length - 1]) {
                    indices = null;
                    return true;
                }
            }
    
            DefaultListModel listModel = (DefaultListModel)target.getModel();
            int max = listModel.getSize();
            System.out.printf("index = %d  max = %d%n", index, max);
            if (index < 0) {
                index = max; 
            } else {
                index++;
                if (index > max) {
                    index = max;
                }
            }
            addIndex = index;
            addCount = alist.size();
            for (int i=0; i < alist.size(); i++) {
                listModel.add(index++, alist.get(i));
            }
            return true;
        }
    
        protected void exportDone(JComponent c, Transferable data, int action) {
            if ((action == MOVE) && (indices != null)) {
                DefaultListModel model = (DefaultListModel)source.getModel();
    
                //If we are moving items around in the same list, we
                //need to adjust the indices accordingly since those
                //after the insertion point have moved.
                if (addCount > 0) {
                    for (int i = 0; i < indices.length; i++) {
                        if (indices[i] > addIndex &&
                            indices[i] + addCount < model.getSize()) {
                            indices[i] += addCount;
                        }
                    }
                }
                for (int i = indices.length -1; i >= 0; i--)
                    model.remove(indices[i]);
            }
            indices = null;
            addIndex = -1;
            addCount = 0;
        }
    
        private boolean hasLocalArrayListFlavor(DataFlavor[] flavors) {
            if (localArrayListFlavor == null) {
                return false;
            }
    
            for (int i = 0; i < flavors.length; i++) {
                if (flavors[i].equals(localArrayListFlavor)) {
                    return true;
                }
            }
            return false;
        }
    
        private boolean hasSerialArrayListFlavor(DataFlavor[] flavors) {
            if (serialArrayListFlavor == null) {
                return false;
            }
    
            for (int i = 0; i < flavors.length; i++) {
                if (flavors[i].equals(serialArrayListFlavor)) {
                    return true;
                }
            }
            return false;
        }
    
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            if (hasLocalArrayListFlavor(flavors))  { return true; }
            if (hasSerialArrayListFlavor(flavors)) { return true; }
            return false;
        }
    
        protected Transferable createTransferable(JComponent c) {
            if (c instanceof JList) {
                source = (JList)c;
                indices = source.getSelectedIndices();
                Object[] values = source.getSelectedValues();
                if (values == null || values.length == 0) {
                    return null;
                }
                ArrayList<String> alist = new ArrayList<String>(values.length);
                for (int i = 0; i < values.length; i++) {
                    Object o = values[i];
                    String str = o.toString();
                    if (str == null) str = "";
                    alist.add(str);
                }
                return new ReportingListTransferable(alist);
            }
            return null;
        }
    
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        }
    
        public class ReportingListTransferable implements Transferable {
            ArrayList data;
    
            public ReportingListTransferable(ArrayList alist) {
                data = alist;
            }
    
            public Object getTransferData(DataFlavor flavor)
                                     throws UnsupportedFlavorException {
                if (!isDataFlavorSupported(flavor)) {
                    throw new UnsupportedFlavorException(flavor);
                }
                return data;
            }
    
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { localArrayListFlavor,
                                          serialArrayListFlavor };
            }
    
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                if (localArrayListFlavor.equals(flavor)) {
                    return true;
                }
                if (serialArrayListFlavor.equals(flavor)) {
                    return true;
                }
                return false;
            }
        }
    }

  3. #3
    ysl530 is offline Member
    Join Date
    Aug 2007
    Posts
    2
    Rep Power
    0

    Default

    Thank you very very much , this is what exactly I want. :)

  4. #4
    smirnoff is offline Member
    Join Date
    Aug 2007
    Posts
    1
    Rep Power
    0

    Default

    Thanks for the example,

    I have just a question. Is it possible In Swing to print a 'bar' or a symbol in a JList for knowing for example where we will insert the data.

    example
    JList1 JList2
    1 4
    2 5
    3

    If a move a number from the JList1 in the JList2, I would like to indicate if I will insert the data before the '4' or before the '5', like with Xp when you want to move a shortcut in all programs for example.

    Sorry for my english.

  5. #5
    _nebu is offline Member
    Join Date
    Jan 2011
    Posts
    1
    Rep Power
    0

Similar Threads

  1. Replies: 2
    Last Post: 06-03-2008, 09:07 PM
  2. Undo Folder Drag and Drop
    By natel in forum Eclipse
    Replies: 0
    Last Post: 04-08-2008, 11:01 PM
  3. Drag and drop
    By abhivenugopal in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 01-30-2008, 02:10 PM
  4. help drag and drop in JTabbedPane
    By RO86 in forum AWT / Swing
    Replies: 0
    Last Post: 08-14-2007, 01:22 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •