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

Similar Messages

  • Drag and Drop Layout with items attached to Page 0 Region Bug

    Hi,
    I have a region on P0 (P0_REGION) and multiple page items (not on page 0) are associated to the region. When I go to "Drag and Drop" the page items I see all the Page Items for the given page and all the Page Items that are linked to a P0 Region. For Example:
    P0:
    Region: P0_REGION
    P100:
    Items: P100_X, Region: P0_REGION
    P200:
    Items: P200_Y, Region: P0_REGION
    Now on P200, click on "Drag and Drop" above P200_Y I'll see P100_X and P200_Y.
    This is a bit of an issue if you have a lot of items that are linked to a region on Page 0 but actually belong to another page.
    Is this a bug?
    Thank you,
    Martin Giffy D'Souza
    [http://apex-smb.blogspot.com/]

    Look at the following link:
    Drag and drop - like the builder?

  • I am getting a "Internal error occurred" message when I try to drag and drop common library items on to my canvas.

    Hi,
    I am getting a "Internal error occurred" message when I try to drag and drop common library items on to my canvas.
    I have noticed that there are a number of these error messages and tried one solution of renaming a couple of files, I tried this and no joy.
    Has any one go a solution for this before I purchase Fireworks please?
    Kind regards,
    Dave G

    I can no longer get Firework CS6 to run - The program loads but without any toolbars/properties etc.  It just has an 'AN INTERNAL ERROR OCCURRED' message that cannot be dismissed.  The only way to close the program is via Task Manager (this is on a Window 8 PC).  I have uninstalled the program, rebooted the PC and re-installed (several times) but it has not resolved the problem.
    Fireworks is part of my Creative Cloud subscription and when reporting this via the live chat I was given the telephone number for Seagate Drives ??
    Anybody got a solution?
    Or, does anybody know how to open native Fireworks CS6 png files in Photoshop *but* with all the Fireworks layers preserved.
    Think I'll also post this as a new topic as the problem is slightly different to SirBasher's issue.

  • 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

  • Page Item Drag and Drop reset all items Displayed Field attribute

    If I use the Drag and Drop feature it resets all items Displayed/Field attribute to yes. Is this just the way it is and it is to bad so sad for Nicholas or is there something I can do to be able to use drag and drop and still retain my setting for the Item's Displayed/Field attribute.
    Any assitance is much appreciated

    Probably the easiest way would be to have 2 arrays that hold
    the data being sent to box A. Just add/or subtract from one that
    you don't care if it changes, and leave the other one alone. When
    you want to reset, just clear Array 2 and populate it again from
    Array 1. For Box B, just reset the contents of the array to nothing
    - myArrayB = new Array({item1:'',item2:''})

  • 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 UI Items vb net

    Hi everybody.
    This is my question:
    I need to use drag and drop onto an item, i really don't have any idea how to do this, if anybody can tell me something i'll be very thankful.
    I'm working with visual basic .net and SBO 2007

    Victor,
    Currently you do not have access to the Drag & Drop functionality of SAP Business One using the SAP Business One SDK.
    Apologies,
    Eddy

  • Upgrade to 3.1.1 broke drag and drop form items

    after upgrading to 3.1.1 when I click the drag and drop icon in items on a form i can then move the fields around and when I hit next the page shows no fields, if I then click apply and look at the form the fields have not moved..

    Hello,
    For me this functionality is still working...
    Do you have the same in another browser? (I'm using FF)
    Regards,
    Dimitri
    -- http://dgielis.blogspot.com/
    -- http://www.apex-evangelists.com/
    -- http://www.apexblogs.info/

  • How to drag and drop item from list to another item in list and change their positions

    I have a list field with multiple items. I want to select one item from list and drag and drop to another item in the list
     after drop item on another item the position of items should be change. (Example:- if I select 1st item from list and drag and drop this item to 4th item in list after drop that item position of both item should be changed 1st item on 4th position and 4th item on 1st position)
    I don't know how to do this.Please help me to find the solution.

    Hello Zoltan,
    I do not believe that kind of option is built into the listboxes, but I was able to have similiar functionalities using property nodes. I have included an example program that I put together.
    The big difference is that instead of dragging, you double click on the item you want to transfer. To highlight items as you go down the list, all you need to do is set the value to that list number.
    Hope this helps you out!
    Attachments:
    Temp.vi ‏33 KB

  • Cannot drag and drop in my playlist to rearrange the song order???

    I have created a playlist in my iTunes 10 and all I want to do is change the order up a bit, so that all the same artists are not lumped together.  Help says I should be able to just drag and drop to reorder my songs in the play list.  However, it won't let me do it.  What am I missing?

    By re-arranging the windows, this appears to work.
    i.e. left window to right window.

  • Wacky Drag and Drop issue with JNLP

    I'm sure I'll have to be a bit more descriptive but I'll just throw this out and see if anyone has any suggestions.
    I've got a swing app which is an administration tool to a rules engine I have built. I distribute the app to users using JNLP 1.2.
    Here's the problem. When I launch the app using JNLP, a portion of the app does not work. There is a panel in which I allow users to drag items off of a tree and onto a panel. They can drag and drop one item but when they attempt to drag and drop a second item it doesn't drop. If I take that same code which is being distributed via JNLP, copy it to the local machine and run it, it works. I can drag and drop all day long.
    There are no exceptions, no errors or funny gooey state things going on. I start the drag, the mouse pointer changes, I hover of the drop zone and let go of the mouse and it appears to drop, but the component does not show. Wacky.
    Does this set off any bells to anyone?
    Thanks,
    - Jay
    App compiled using 1.4.1_01.

    Ah ha.. Yes this does seem to the issue. Thanks for the response. I've tested it on a couple of machines and it works on the one's with 1.4.1 and it doesn't seem to work on 1.4.0 jre machines.
    NEW Question though, if I set my .jnlp to:
    <j2se version="1.4.1+"/>
    I get the 'ol 'Error Code 11 (11 Could not locate requested version'
    Is there any way to get this guy to auto-install???
    I've installed JRE 1.4.1 manually and it doesn't seem to pick that up either.
    Thanks...

  • Implement Drag and drop functionality in my application

    I want to drag image from one UIImageView to other UIImageView.
    Is there any event handle to this drag and drop functionality.
    Any one have different idea to handle this. than please reply.
    Any coding idea related to this?

    it is possible but u have to write some advance code to handle plz mention ur Forms version and other info
    Forms 10g and above possible with Java beans
    Forms 6i there is a demo in forms online help ........ Search DRAG
    To enable drag and drop on an item:
    1     Attach the PL/SQL library DRAG.PLL, which contains the  Mouse package, to your module.
    2     Create a WHEN-MOUSE-DOWN trigger on each item that can be dragged.  From this trigger, call the Click routine from the Mouse package.
    3     Create a WHEN-MOUSE-MOVE trigger on each item that can be dragged.  From this trigger, call the Move routine from the Mouse package.
    4     Create a WHEN-MOUSE-UP trigger on each item that can be dragged.  In this trigger, write your application specific code.Baig
    [My Oracle Blog|http://baigsorcl.blogspot.com/]

  • Drag and drop panel

    I plan on writing a "drag and drop" interface that lets a user place things on a "canvas" and move them around. I will then let the user connect them with lines. Such things could be nodes in a network, one of the ideas I've had for using it. Basically this will allow visualization of whatever is happening behind the scenes, such as routing algorithms (etc).
    My plan at the moment is to have a canvas class and a can-be-placed-on-canvas class. The canvas object is in charge of handling the mouseclicks and moving of the objects. It will have an add() method which lets you add the objects to visualize, probably storing them in a collection.
    The objects placed on the canvas will have some form of .draw() method that returns what should be drawn to visualize them. I'd like to separate this away from the canvas so that different objects can be drawn.
    The problem I'm having at the moment is the actual dragging and dropping of the items. I could iterate over every object and see if it appears where the user is clicking, perhaps by comparing object.left + object.width and object.top + object.top to see if it encompasses the cursor. Surely this will be slow though and I'm not sure it would be the most efficient way of doing it.
    Another problem is z-order, I could assume that items are drawn according to their position in the collection. Then, when checking where a user clicks, iterate over the collection backwards as the item "on top" will be the first one found when going in the backward direction.
    I am presuming I will use a Graphics2D as the canvas, encompassed in a JComponent with an overridden .paint(). However, if this isn't the best way any other ideas would be nice.
    Before I start coding, does anybody have any ideas how I could design this if my suggestions do not make sense? Or are there are any significant flaws in the way I plan to do it?
    Thanks.

    So you are suggesting I use JComponent (which makes
    sense) and add a listener to it? That listener could
    probably be the canvas, which would then handle the
    dragging and dropping. I could also override paint()
    (including calling super.paint(), as I've found I have
    to do from past experience) in order to give my
    components the look I want.Yeh, Something like that. Everything you want to draw on your Canvas should be derived from JComponent
    (perhaps even JButton (depends on what you want to do)). The listener can be the JCanvas or perhaps
    a set of seperate behaviour classes that implement dragging (and optionally other behaviours such as
    context sensitive popup menus). Or you could have multiple listeners for different aspects of the behaviour
    Thanks for your suggestions, I guess the only
    difficulty now would be implementing the moving. Any
    ideas how the moving could be done?Make a single mouseListener. Register it with all the JComponents and listen for the MouseEvent.MOUSE_DRAGGED Event. When this occurs you obtain the Source of the event and change
    its coordinates (using setLocation or reshape)
    matfud

  • Reorder items in JTree using drag-and-drop

    Title says it all: before I start re-inventing the wheel, any code out there?
    Think of the code that I need as an outliner.

    Did you ever find a solution to this. I'm looking to implement a similar interface using a JList where the user can reorder drawing layers by dragging and dropping.
    I'm temped to use a scrollpane and roll my own drag reorder code, so any supported behaviors would be welcome.
    thanks,
    Steven

Maybe you are looking for

  • Save and reuse elements in a new Project

    Firstly, ^5 on Edge Reflow! I love it to bits! Will you guys allow to save elements to the assets library in order to use those elements in a new Project? (not a new page in the current project.) Guess similar to an predefined assets library where yo

  • Lenovo G50-70 HDD Ticking Sound

    Hi I bought my laptop last august, now its HDD makes ticking sound when idle but it is fully functional. That sound is very annoying .

  • Error in skill profile under ESS career and job

    Hi When i am accesing skill profile iveiw under careen and job in ESS if i click add skill profile it is displaying the error " Unable to find a root object for the object type specified  " Thanks, faizol

  • Stop Crystal from Prompting for Parameters

    Hi there, I am trying to stop Crystal from prompting for a parameter that has the Optional Prompt flag set to True as I want to use the HasNoValue attribute to retrieve all records when there is not a specific value sent to the parameter. When the pa

  • [UDP fast age support for ACE Module]

    Hello, I'm testing 2 ACE modules running A3.0.0 for DNS load balancing (UDP). We're testing this by using a DNS query generator that (always) seems to use the same UDP source port when originating these queries. At the moment, the ACE module is hardl