JList - drag and drop

Hi,
I'm struggling with getting my program outfitted with a drag and drop function in and between a few JList components. (I'm using NetBeans IDE 6.7)
I have four JLists of which only one I want to enabled drag and drop rearrangement of the strings. Furthermore I would like to enable dragging from the other three lists into the rearrangeable list (which may be empty!).
I've searched for answers but I just can't manage to translate the answers on other forums into a usable solution for my program... I am relatively new to Java and NetBeans, so I would appreciate if you could keep the answers simple... (if possible).
What I know about this problem already:
- if i set dragEnabled to true, I can drag text into e.g. a TextField without further complications

JTextComponents have preinstalled TransferHandlers that make it possible to simply call setDragEnabled(true) and you are good to go. However, with most other components, you need to install a custom TransferHandler (ie call list.setTransferHandler() ) to get the job done.
Here is a sample of the code you need: ListTransferHandler
ICE

Similar Messages

  • JList drag and drop to reorder items

    I like to see a implementation of a JList supporting drag and drop to reorder items. The solution has to work with any object type in the datamodel.

    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class ReorderList {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ReorderList().makeUI();
       public void makeUI() {
          Object[] data = {"One", "Two", "Three", "Four", "Five",
             "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"
          DefaultListModel model = new DefaultListModel();
          for (Object object : data) {
             model.addElement(object);
          JList list = new JList(model);
          MouseAdapter listener = new ReorderListener(list);
          list.addMouseListener(listener);
          list.addMouseMotionListener(listener);
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(200, 200);
          frame.add(new JScrollPane(list));
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    class ReorderListener extends MouseAdapter {
       private JList list;
       private int pressIndex = 0;
       private int releaseIndex = 0;
       public ReorderListener(JList list) {
          if (!(list.getModel() instanceof DefaultListModel)) {
             throw new IllegalArgumentException("List must have a DefaultListModel");
          this.list = list;
       @Override
       public void mousePressed(MouseEvent e) {
          pressIndex = list.locationToIndex(e.getPoint());
       @Override
       public void mouseReleased(MouseEvent e) {
          releaseIndex = list.locationToIndex(e.getPoint());
          if (releaseIndex != pressIndex && releaseIndex != -1) {
             reorder();
       @Override
       public void mouseDragged(MouseEvent e) {
          mouseReleased(e);
          pressIndex = releaseIndex;     
       private void reorder() {
          DefaultListModel model = (DefaultListModel) list.getModel();
          Object dragee = model.elementAt(pressIndex);
          model.removeElementAt(pressIndex);
          model.insertElementAt(dragee, releaseIndex);
    }edit Reduced a few LoC
    Edited by: Darryl.Burke

  • Explorer to JList Drag and Drop??

    Totally stuck on this one, need an example that allows a user to drag a file from Windows Explorer to a JList, thereby adding the filename to the JList.. looked all over and couldn�t manage to get it working, some demo code would be excellent..
    A bit urgent thanks..

    Thx. Worked through that article a few days ago, didn�t help much..
    I've almost managed to get it all working, wish swing had a better feature set, i shouldn�t have to write 200+ lines to get something as simple as windows explorer drag to JList and JList drag sort working, should be available via a simple dragSetEnable() function.. anyway enough ranting back to coding..

  • JList Drag and Drop issues

    I am having a weird problem. I have a JList, and it has draggable elements in it. When i click and drag a selected item it drags jsut fine and DnD suceeds. when i try to drag an unselected item it fails, though the selection changes.
    is there any way to change the selection and start draging with jsut hte one click?
    thanks

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TestJList extends JFrame {
        public TestJList() {
            initComponents();
        private void initComponents() {
            list = new JList();
            textarea = new JTextArea();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test JList: dragEnabled");
            list.setModel(new AbstractListModel() {
                String[] strings = { "One", "Two", "Three" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    list.setDragEnabled(true);
    list.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent evt) {
    listMouseMoved(evt);
    getContentPane().add(list, BorderLayout.WEST);
    textarea.setBackground(new Color(255, 255, 204));
    textarea.setBorder(new LineBorder(new Color(0, 0, 0)));
    getContentPane().add(textarea, BorderLayout.CENTER);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
    private void listMouseMoved(MouseEvent evt) {
    int index = list.locationToIndex(evt.getPoint());
    list.setSelectedIndex(index);
    public static void main(String args[]) {
    new TestJList().setVisible(true);
    private JList list;
    private JTextArea textarea;

  • Drag and Drop issue in Jlist - Transferhandler not working

    Hi all,
    I have a problem associated with the drag and drop of components into a Jlist.
    When I drag component out of a Jlist, the control reaches inside transfer handler, but when I try to insert a component into the Jlist, the control does not reach inside Jlist transfer handler.
         jlist.setDropMode(DropMode.INSERT);
         jlist.setDragEnabled(true);
         jlist.setTransferHandler(new TransferHandler()
                   List fileList;
                   boolean export = false;
                   List<File> newList = null;
                   protected Transferable createTransferable(JComponent c)
                        System.out.println("inside handler");
                                    ..............................Please help me with this issue.
    Any help in this regard will be well appreciated with dukes.
    Regards,
    Anees

    AneesAhamed wrote:
    Hi all,
    I have a problem associated with the drag and drop of components into a Jlist.
    When I drag component out of a Jlist, the control reaches inside transfer handler, but when I try to insert a component into the Jlist, the control does not reach inside Jlist transfer handler.
    jlist.setDropMode(DropMode.INSERT);
    jlist.setDragEnabled(true);
    jlist.setTransferHandler(new TransferHandler()
                   List fileList;
                   boolean export = false;
                   List<File> newList = null;
                   protected Transferable createTransferable(JComponent c)
                        System.out.println("inside handler");
    ..............................Please help me with this issue.
    Any help in this regard will be well appreciated with dukes.If you're wondering why your createTransferable() method is not called when you drag from some other component and drop into the list it is because createTransferable() is called when you start dragging. So it would be the TransferHandler of the source component, not your target list, that has its createTransferable() called in that case.
    When the list is the target of a drag&drop you should see the canImport() method of your TransferHandler being called. Do a System.out(0 in that method as well and see if that is the case.

  • Drag and Drop items among JList

    Hi,
    I want to drag item from one JList and drop into another JList using JFrame in java Swing. Please provide me code for this.
    Thanks
    Nitin

    You need to implement a drag-and-drop (dnd) behaviour between your swing components.
    Like most programming tasks it looks harder than it really is. Basically you need a DragSource and a DropTarget with a Transferable object in between. This Transferable object is the object from your list.
    Here is Sun's tutorial on it... http://java.sun.com/docs/books/tutorial/dnd/
    Good luck.

  • Drag and Drop between Jlists

    Hello,
    I have two JLists, one containing music tracks (not actual tracks, just info like name, artist duration etc), and the other is a Playlist.
    So I want to be able to drag items from the database of tracks (Jlist one) to the playlist (Jlist two).
    I have looked how this is done and here is some of the code that I have:
        //allow the mouse to drag and drop tracks
        private class DragMouseAdapter extends MouseAdapter {
            public void mousePressed(MouseEvent e) {
                JComponent c = (JComponent)e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.COPY);
            //allow tracks to be dragged and dropped
            lstDatabase.setDragEnabled(true);
            MouseListener listener = new DragMouseAdapter();
            lstDatabase.addMouseListener(listener);
            //allow tracks to be dragged and dropped
            lstPlayList.addMouseListener(listener);
            lstPlayList.setTransferHandler(new TransferHandler("text"));Nothing seems to happen
    Any Ideas?
    Cheers

    The swing tutorial on "How to Use Drag and Drop" has a working example using JLists:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html#complex

  • How to handle (drag and drop) and Action Event in a JList?

    I am having many JList,
    On click of an element in JList I am loading a image in JSP.
    But If I try to drag and drop one image from one bucket to another bucket Iam not getting any problem,
    But I when I drag all the images from the target List to some other List and make the target List empty.
    Now If I try to move the image from source list to the target list Iam getting this error,
    Exception in thread "AWT-EventQueue-6" java.lang.NullPointerException
         at pdfViewer.NewFileSegregater$24.valueChanged(NewFileSegregater.java:1944)
         at javax.swing.JList.fireSelectionValueChanged(Unknown Source)
         at javax.swing.JList$ListSelectionHandler.valueChanged(Unknown Source)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
         at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
         at javax.swing.DefaultListSelectionModel.insertIndexInterval(Unknown Source)
         at javax.swing.plaf.basic.BasicListUI$Handler.intervalAdded(Unknown Source)
         at javax.swing.AbstractListModel.fireIntervalAdded(Unknown Source)
         at javax.swing.DefaultListModel.addElement(Unknown Source)
         at pdfViewer.NewFileSegregater.actionPerformed(NewFileSegregater.java:2918)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener$Actions.actionPerformed(Unknown Source)
         at javax.swing.SwingUtilities.notifyAction(Unknown Source)
         at javax.swing.JComponent.processKeyBinding(Unknown Source)
         at javax.swing.KeyboardManager.fireBinding(Unknown Source)
         at javax.swing.KeyboardManager.fireKeyboardAction(Unknown Source)
         at javax.swing.JComponent.processKeyBindingsForAllComponents(Unknown Source)
         at javax.swing.JComponent.processKeyBindings(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Please help me how to solve this problem..

    Er, sure. In the class pdfViewer.NewFileSegregater on line
    1944 (!), in the valueChanged() method, something is pointing to
    null.
    That method is being called from
    pdfViewer.NewFileSegregater.actionPerformed() on line
    2918 (!!).
    Of course, none of us know what's going on in those code
    segements but you. And for the record, that's not how to spell
    Segregator.

  • JList TransferHandler Drag and Drop -- w/Autoscroll?

    Hi everyone,
    Just wondering if anyone has written a TransferHandler for a JList that permits drag and drop reordering, that will also autoscroll its parent JScrollPane if dragging to a boundary? Don't want to reinvent the wheel!
    Thanks.
    Alex

    Rolled my own, [can see it here|http://forums.crm.saeven.net/blog.php?b=2]
    Hope it helps.

  • Drag and Drop(JList )

    Hi there,
    I have a problem with implementing Drag and Drop into my JList. As my class is a JPanel and there is a JList which is needed to have a drag and drop feature where it enable user to drag and drop to another JList. So I would like to ask how can i go about doin it without writing a new JList Class which implements the DropTargetListener, DragSourceListener, DragGestureListener to the JPanel.
    Thanks...

    JTextComponents have preinstalled TransferHandlers that make it possible to simply call setDragEnabled(true) and you are good to go. However, with most other components, you need to install a custom TransferHandler (ie call list.setTransferHandler() ) to get the job done.
    Here is a sample of the code you need: ListTransferHandler
    ICE

  • Drag and Drop an email from OutLook to JList.

    Hi All,
    Can anyone of you please guide me on how to implement drag and drop an email from microsoft outlook to JList.
    Thanks in advance.!
    Amit

    It might just be Microsoft not using standards? I remember having a similar situation - I had an application that could have a zip entry fron 7-zip drag-and-dropped into it (came over as plain text, or maybe an InputStream, can't remember), but when you drill into a zip file with Windows (Vista at least), and try to drag-and-drop a zip entry from Windows Explorer, Java shows no dataflavors available. I just assumed Microsoft wasn't exporting the zip entry in any standard format (such as plain text).
    Sorry, I know that wasn't very helpful, just thought I'd share a similar experience. :)

  • Drag and Drop to Change Order in a List

    Does anyone know of an example where there is the ability to drag and drop elements in a list and thus change their order? (I.E. drag item one below item two and then item one and two change locations)
    Thanks!

    Check out http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html
    There's an example towards the end of the page for drag-and-drop between 2 JLists. Might be a good starting point.

  • 1.4.2 JList to JList drag n drop example?

    Could anyone provide (or point me to) a jsdk1.4.2 example of drag and drop from one JList to another? What I'd really like is multiple (say 3 or 4) JLists that can all drag and drop multiple items between each other (supporting multi-select).

    Look for ExtendedDnDDemo [url http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html]here.

  • Implementing drag and drop across components with drag image...

    Hey all,
    Finally got the hang of drag and drop. Not too hard, but a little time consuming. I found an article showing how to capture and drag a BufferedImage within a JTree. When you click and drag a node, it creates a BufferedImage of the node on screen and "ghosts" it a bit, which has a very appealing effect.
    However, when I try to drag this image to a JList component, it disappears. So I created the same affect in the JList component. Now you can drag the image from the tree to the list and vice versa. However, the problem is, the image does not "fly over" the borders of the two components (butted up against each other) with the mouse. The image seems to go under the borders, while the mouse floats above everything.
    What I would like to do is be able to drag the image all over the application, perhaps even the desktop in the case of a SDI application. I want to be able to see this image drag from my Java app over the Windows Explorer folder, just like how you can do that with Windows Explorer, dragging an image of the selected node into any app that supports the drop. I know we can handle the "transfer" data from explorer and vice versa, but how to be able to keep an image with the mouse?
    My best guess is somehow using the Glass pane, grabbing a ref to its BufferedImage (if that is even what is there), and drawing the dragged item in that pane. But, then, how will the image move over the desktop outside of the app, where a glass pane is not?
    Is there a way to draw on top of anything, anywhere, but still be able to redraw the background as the image moves with the mouse? There are times where the image may be big, so I don't want to have to capture the underlying screen as an image covering the size of the drag image to restore it as the drag image moves around.
    Thank you.

    We know cursors support some degree of transparence because they have shapes other than blocks.
    I've done some playing around with
    Toolkit.getDefaultToolkit().createCustomCursor(....);The sad news is, it seems that as soon as a pixel's alpha value is greater than 0, it automatically becomes 100% opaque.
    The best you can do, is to take your image, and divide it into a pixel-checkerboard, and set the alpha value of alternating pixels to 0.
    e.g.
    BufferedImage i = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
            int[] data = ((DataBufferInt)i.getRaster().getDataBuffer()).getData();
            boolean on = true;
            for (int z=0; z<data.length; z++)
                if (on)
                    data[z] = 0xffffffff;
                else
                    data[z] = 0x00000000;
                on = !on;
                if (z%32==0) on = !on;
            Cursor hazyWhite = Toolkit.getDefaultToolkit().createCustomCursor(i, new Point(0,0), "hw");

  • Cannot drag and drop file from photos app to photoshop

    Hi,
    I'm trying to open a file saved in my Photos library in Photoshop. Previously in iPhoto I could drag and drop the file to open in other applications including Photoshop but this functionality appears to be missing in the new Photos app. Am i missing something? Or is there another way to do it?
    thanks

    Tristan,
    I am stuck in the same place. Perhaps we could work on this together.
    I am trying to drag a single item from a JList to a text editor, Word, etc. I have two problems:
    1) I can't seem to get just the item in the JList to drag. It wants to drag the entire JList component.
    2) How does one define the remote application as the drop target? Have not found any examples either.
    Is the drop target actually the system clipboard?
    Rp

Maybe you are looking for

  • How do I remove credit card info?

    I want to remove credit card info from my account. How do I do that?

  • Purchased Songs not Playing

    Hey, I just recently got my first two songs from the music store. I have had some other songs from CDs, but wanted to start downloading. I downloaded "White and Nerdy" and "Amish Paradise" by Weird Al. The problem is, I go to play them and for a brie

  • A verticle red line suddenly has appeared on my monitor

    I was lookiing at a video on Youtube and tried to upload it. It didn't. But, suddenly now I have a verticle red line on my monitor which i cannot get rid of. Anyone out there have an idea what could be wrong? thanks.

  • Widget: "screenshot plus", not working in leopard, etc...

    widget: "screenshot plus", not working in leopard. another bug? kids digital camera opens iphoto but doesnt appear on desktop to eject w/out errors. another bug? if i havnt registered leopard yet, can i sell it, cuz i think i might not want it now.

  • New to IS-Oil

    Hi guys i am really new to IS Oil.. just need some informations regarding MM module in IS Oil... 1) any PDF files about the MM process ? 2) what are the important transactions used in MM IS Oil? also how we navigate is oil access menu??? your help is