Drag a JLabel, drop in a JList

I'm trying to implement a drop-and-drag feature in my program.
I have a class Book, which extends a JLabel with and ID field (as a string) and a get and set method for the ID in it, as well as a toString method which returns the ID.
I need to drag the label over a JList and add the label's ID to the list, directly below the selected index over which the mouse dropped.
So far i have tried to override the transferhandler with example String and List handlers i found on the site (at http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/ListTransferHandler.java and http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/StringTransferHandler.java ) however, it seems the problem keeps getting bigger the more i try to edit them.
Also, i have tried to implement Serializable and Transferable Book's, but I'm not entirely familiar with how to use the dataflavors, so that could also be causing the problem.
I have tried a few possible scenarios with the transfer handler and so far this is getting me the most results:
public class dragtest extends JPanel {
public dragtest() {
super(new GridLayout(3,1));
add(createArea());
add(createList());
add(createBookcase(17));
private JPanel createList() {
DefaultListModel listModel = new DefaultListModel();
listModel.addElement("List one");
listModel.addElement("List two");
listModel.addElement("List three");
JList list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setPreferredSize(new Dimension(400,100));
// do not allow list items to be dragged
list.setDragEnabled(false);
// list.setDropTarget();
// DropTarget dt = new DropTarget();
// list.setDropTarget(dt);
list.setTransferHandler(new ListTransferHandler());
JPanel panel = new JPanel(new BorderLayout());
panel.add(scrollPane, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createTitledBorder("List"));
return panel;
private JPanel createBookcase(int amount) {
JPanel bookCase = new JPanel();
int X1 = 30; // height from top
int X2 = 20; // height to bottom
int Y1 = 20; // distance from sides
int Y2 = 10; // distance between images
int Z1 = 60; // width of image
int Z2 = 80; // height of image
int numLabelsInCol = 5;
int numDone = 0;
int x = 0;
for (int y = 0; y < numLabelsInCol; y++) {
if (numDone < amount) {
Book lbl = new Book(numDone, "address");
lbl.setBounds( (Y1 + y * (Z1 + Y2)), (X1 + x * (Z2 + X2 + X1)), Z1, Z2);
bookCase.add(lbl);
String text = lbl.ID;
lbl.setText(text);
numDone++;
lbl.setTransferHandler(new TransferHandler("text"));
MouseListener listener = new DragMouseAdapter();
lbl.addMouseListener(listener);
bookCase.setPreferredSize(new Dimension(400, 100));
return bookCase;
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);
I realise it might be a little unconventional, the way i implement the transfer handler, but this actually prints out the ID on a JTextArea, however a list does not even react when i drag or drop the label over it. It does not even show a shaded area under which the mouse is.
I have tried a multitude of examples but none of them have dealt with this. The only one which deals with JLabels dropped on a JList does not care for the order, however my program focuses on it.
Please could anyone help?

1) Swing related questions should be posted in the Swing forum
2) When you poste code use the "code" formatting tags so the code retains its original formatting
Using the ExtendedDnDDemo, from the Swing tutorial you referenced above, as the test program I created the following method:
    private JPanel createLabel() {
         JLabel label = new JLabel("Dnd Label");
        label.setTransferHandler(new LabelTransferHandler());
        label.addMouseListener( new MouseAdapter()
             public void mousePressed(MouseEvent e)
                 JComponent c = (JComponent)e.getSource();
                 TransferHandler handler = c.getTransferHandler();
                 handler.exportAsDrag(c, e, TransferHandler.COPY);
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(label, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createTitledBorder("Label"));
        return panel;
    }And the following class:
* LabelTransferHandler.java is used by the 1.4
* ExtendedDnDDemo.java example.
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
public class LabelTransferHandler extends StringTransferHandler {
    // Get the text for export.
    protected String exportString(JComponent c) {
        JLabel label = (JLabel)c;
        return label.getText();
    //Take the incoming string and set the text of the label
    protected void importString(JComponent c, String str) {
        JLabel label = (JLabel)c;
        label.setText(str);
    protected void cleanup(JComponent c, boolean remove) {
}

Similar Messages

  • 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 issue between JLists

    Hi,
    I am trying to implement DnD into my application between different JLists, but I can't get it to work.
    In my application I have two different panels, a SearchPanel, and a DataPanel.
    On each panel I have two JLists, one which contains strings, another which contains a custom class called Goals.
    The lists on the searchpanels are the source of the drag action, each with their own DataFlavor. I wanted each of the two JLists on the datapanel to accept both flavors, so I implemented the DropTargetListener on the DataPanel. I figured I could determine where the drag came from depending the DataFlavor of the Transferable, but somehow, he treats the GoalTransferable as Strings, and adds them to the wrong list...
    Is there anyone that knows were I might have made a mistake?
    Here is some code:
    The search panel with relevant bits and pieces, th materialsList contains Strings, the goalsList contains Goal objects
    public class SearchPanel extends JPanel implements ActionListener, DragGestureListener, DragSourceListener {
       private JList materialsList;
       private JList goalsList;
       private void createGUI () {
          materialsList = new JList();
          materialsList.setDragEnabled(true);
          goalsList = new JList();
          goalsList.setDragEnabled(true);
          DragSource dragSource = DragSource.getDefaultDragSource();
          dragSource.createDefaultDragGestureRecognizer(goalsList,DnDConstants.ACTION_COPY, this);
       public void dragGestureRecognized(DragGestureEvent dge) {
          Goal selection = (Goal)goalsList.getSelectedValue();
          Transferable transferable = new GoalTransferable(selection);
          dge.startDrag(new Cursor(Cursor.MOVE_CURSOR), transferable);
       public void dragDropEnd(DragSourceDropEvent dsde) {}
       public void dragEnter(DragSourceDragEvent dsde) {}
       public void dragExit(DragSourceEvent dse) {}
       public void dragOver(DragSourceDragEvent dsde) {}
       public void dropActionChanged(DragSourceDragEvent dsde) {}
    }For the GoalTransferable class:
        public class GoalTransferable implements Transferable {
            private DataFlavor goalFlavor = null;
            private DataFlavor supportedFlavors[] = {goalFlavor};
            private Goal object;
            public GoalTransferable (Goal o) {
                object = o;
                try {
                    goalFlavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=nl.lycos.fierensyves.jsv.data.Goal");
                } catch (Exception e) {}
            public Object getTransferData(DataFlavor df)
                throws UnsupportedFlavorException {
                if (isDataFlavorSupported (df))
                    return object;
                else
                    throw new UnsupportedFlavorException(df);
            public boolean isDataFlavorSupported (DataFlavor df) {
                return (df.equals (goalFlavor));
            public DataFlavor[] getTransferDataFlavors () {
                return supportedFlavors;
        }And finally for the datapanel:
    public class DataPanel extends JPanel implements ActionListener, MouseListener, KeyListener, ChangeListener, DropTargetListener {
         private JList materials;
         private JList goals;
                    private DataFlavor goalFlavor = null;
         public ActivityFrame (DataReader data) {
              this.materials = new JList();
                                    DropTarget materialsTarget = new DropTarget(materials, this);
              this.goals = new JList();
              this.goals.addMouseListener(this);
                                    DropTarget goalsTarget = new DropTarget(goals, this);
                                    this.goals.setTransferHandler(new GoalTransferHandler(goals));
                                    try {
                                                    goalFlavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=nl.lycos.fierensyves.jsv.data.Goal");
                                    } catch (Exception e) {}
                                    public void drop (DropTargetDropEvent dtde) {
                                    if (dtde.isDataFlavorSupported(goalFlavor)) {
                                                     //import goal
                                    } else {
                                                     //import material
                                         TreeSetListModel model = (TreeSetListModel)this.materials.getModel();
                                                    String material = "";
                                                    try {
                                                                     material = dtde.getTransferable().getTransferData(DataFlavor.stringFlavor).toString();
                                                    } catch (Exception e) {}
                                         model.addElement(material);
                                         this.materials.setModel(model);
                                         this.materials.updateUI();
                    public void dragEnter(DropTargetDragEvent dtde) {}
                    public void dragExit(DropTargetEvent dte) {}
                    public void dragOver(DropTargetDragEvent dtde) {}
                    public void dropActionChanged(DropTargetDragEvent dtde) {}       
    }greetings,
    fifijr

    That does not exist - the workaround (maybe permanent solution - who knows) is
    File menu ==> export
    And BTW if you are not backingup all the time you are 100% guarenteed to lose all of your files and photos sooner or later
    LN

  • 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.

  • How can i do drag from cl_column_tree_mode drop to cl_gui_alv_grid ???

    Hi,
    I have building a program that will have one split screen and one of them has cl_column_tree_mode at top, and the other has cl_gui_alv_grid at bottom.
    I can Drag And Drop Lines From ALV GRID to TREE and i can use ONDRAG event of ALVGRID, DROP event of TREE Control and ONDROPCOMPLETE event of ALVGRID.
    But when i try to reverse it as like that Drag From TREE to ALVGRID, just DRAG event of TREE is triggering.
    I have implemented end registered ONDROP event for ALVGRID but it is no triggering.
    Have i something which missed ? Some of code at the above.
    *****************CODE****************************************
    *I created Application Ocject, Custom Container and Spliiter in here
    **       Definition of drag drop behaviour
        create object behaviour_top.
        call method behaviour_top->add
            exporting
                  flavor = 'LINEFROM' "I dont know where i can use this
                  dragsrc = 'X'
                  droptarget = 'X'
                  effect = cl_dragdrop=>move.
        call method behaviour_top->add
             exporting
                   flavor = 'LINETO'   "I dont know where i can use this
                   dragsrc = 'X'
                   droptarget = 'X'
                   effect = cl_dragdrop=>move.
        call method behaviour_top->get_handle
             importing handle = handle_top. "I am not sure that i can use this handle for both TREE Nodes and ALV Rows, But i am using it for both.
    ******************************   TREE   ********************************
    *   CREATE TREE
        ls_treemhhdr-heading = 'Nakliye ve Makaralar'.
        ls_treemhhdr-width   =  35.
        create object gref_column_tree
         exporting
         node_selection_mode   = cl_column_tree_model=>node_sel_mode_single
         item_selection        = space
         hierarchy_column_name = 'NUMBER'
         hierarchy_header      = ls_treemhhdr.
        call method gref_column_tree->create_tree_control
          exporting
            parent                       = container_1    .
    *   Events for tree control
        set handler g_application->handle_tree_drag for gref_column_tree.
        set handler g_application->handle_tree_drop for gref_column_tree.
    *   Build TREE
        perform build_tree using gref_column_tree. "I use HANDLE_TOP in this when creating nodes.
    ******************************   TREE   ********************************
    ****************************  ALV GRID  ********************************
    *   create ALV Grid
        create object alv_grid
                      exporting i_parent = container_2.
    *   Events alv control
        set handler g_application->handle_alv_drag for alv_grid.
        set handler g_application->handle_alv_drop for alv_grid.
        set handler g_application->handle_alv_drop_complete for alv_grid.
        gs_layout-grid_title = '&#304;s Listesi'.
        gs_layout-s_dragdrop-row_ddid = handle_top. "I think this is a important thing
        call method alv_grid->set_table_for_first_display
             exporting is_layout        = gs_layout
             changing  it_fieldcatalog  = gt_fieldcat
                       it_outtab        = i_tabout[].
    ****************************  ALV GRID  ********************************
    *I have implemented all methods for this class, it hink its not important to see *which code its has, important is why its not triggering.
    class lcl_application definition.
      public section.
        data: next_node_key type i.
        methods:
    *   ALV EVENTS
        handle_alv_drag for event ondrag of cl_gui_alv_grid
            importing e_row e_column e_dragdropobj,
        handle_alv_drop for event  ondrop of cl_gui_alv_grid
            importing e_row e_column es_row_no e_dragdropobj,
        handle_alv_drop_complete for event ondropcomplete of cl_gui_alv_grid
            importing e_row e_column e_dragdropobj,
    *   TREE EVENTS
        handle_tree_drag for event drag  of cl_column_tree_model
            importing node_key item_name drag_drop_object,
        handle_tree_drop for event drop  of cl_column_tree_model
            importing node_key drag_drop_object,
        handle_tree_drop_complete for event drop_complete of cl_column_tree_model
            importing node_key ITEM_NAME drag_drop_object.
    endclass.

    Thanks kaipha,
    in examples in SE83 i have noticed that i have to create an inctance for drag drop object when drag starts.
      method handle_tree_drag.
        data: "local_node_table type node_table_type,
              new_node type mtreesnode,
              dataobj type ref to lcl_dragdropobj_from_tree,
              l_keytxt(30) type c.
        catch system-exceptions move_cast_error = 1.
    *           create and fill dataobject for events ONDROP and ONDROPCOMPLETE
                create object dataobj. "When i create dataobj in here
                move node_key to dataobj->node_key.
                drag_drop_object->object = dataobj. "And when i call this method, ALV Drop event has begin triggered
        endcatch.
        if sy-subrc <> 0.
          call method drag_drop_object->abort.
        endif.
      endmethod.

  • Can Drag But Not Drop

    Hello. This is my first time posting. I have a problem I cannot solve. I was able to DRAG and DROP my iTunes songs in the order I wanted them. But cannot do so anymore. Something must have changed somewhere. I saw somewhere on another forum to sort by the first column on the left(song order number) , but I cannot find this anywhere.
    Please help me as I love iTunes player but am getting ready to go back to windows media player. Thanks in advance for your help.

    I do not have an iPod. I want to reorder the songs I downloaded to my hard drive to the order I want them.
    I just made a new playlist and dropped these songs into it. They became out of the order that I had them in. Now THEY will not drop either. I am sick of iTunes. It is becoming more trouble than it is worth. I NEVER had this problem with Windows Media Player. At least it is dependable. I know my songs will stay in the order I put them.
    I like to keep my songs all together by artist abd genre. All one Artist together plus the genre that the artist belongs. I had them placed in this order by making a new playlist and now that playlist will NOT let me rearrange these songs like I had them. I cannot DROP ANY SONG ON ANY PLAYLIST. Something is happening because at first I could arrange them and then they became mixed up and now I cannot drop them where I want them. I can drag but they go right back to the position they were in This IS ON A new playlist I just made.

  • This is a second question on the same topic. I want to create multiple drags to each drop. I give the drags group names. Step three: run line to drops. Step 4: click object actions Step 5: unclick all but the one group name. It works for 2 out of 3 groups

    I hope that someone will answer this. I want to create a drag and drop.  Each drop has multiple drag answers. I group the drags and give them a Type name. I initial the drops. I go to Object actions. I unclick "accept all" I unclick all but the group I want to go to that drop.  When I preview, two of the drops accept the three choices that they are supposed to accept. But the first one I try, only accepts one choice and lets the others bounce back.  I'd also like to have a reset button which I can't find.  I've spent hours and hours working on this.

    Got it.  When you go to unclick all the choices except the group you want, you have to also change the count. Even if the drags are in a group, the count still considers them individually

  • Added drag support breaks drop support

    I have a Swing app (running on WIndows), which consists mainly of a Jtable with a list of files in it, one file per row. I wanted to be able to open files in the JTable using drag and drop, so Ive created a subclass of DropTarget and set it for my frame with setDropTarget() and it works fine, I can now drag and drop files from Windows Explorer. I set the drop target for the frame rather than the table because I wanted the user to be able to drop the files anywhere on the application.
    I then wanted to add dragging files from the Jtable to other applications to be able to make copies of the file. So I setDragEnabled() on the table and setTransferHandler() on the table and created appropriate TransferHandler and Tranferable subclasses. Now I can can drag files from the table ok, but unfortunatelly I can no longer drop files onto the frame, it just shows the no-entry sign when I try to. I don't see why enabling drag support in the table breaks drop support in the frame, but it does - what am I doing wrong?
    thanks Paul

    paultaylor wrote:
    setTransferHandler() on the table ... I can no longer drop filesTry overriding "importData" in TransferHandler.

  • Does anyone know why the mixed signal graph stops allowing traces to be drag'ed and dropped between different plot areas?

    I have a mixed signal graph that allows me to drag and drop my traces between the plot areas,  then it stops allowing it.
    If I start with a new graph it allows it but eventually stops allowing it.
    I have 4 XY charts feeding the one mixed singal graph through a bundle function, then I run it once and drag my traces to the correct plot area
    and hope that it keeps working.
    Best Regards
    Tim C.
    1:30 Seconds ARRRGHHH!!!! I want my popcorn NOW! Isn't there anything faster than a microwave!

    Hi Tim,
    That sounds like some interesting behavior.  Can you reproduce what you were seeing, or have you continued to be able to drag the signals to other plots since you saved and reopened your program? 
    Jennifer R.
    National Instruments
    Applications Engineer

  • Help: Flash Drag, Rotate and Drop

    Hi, it's simple i know some of you knows how to do this. This
    is just a sample idea wheel, see picture:
    http://www.geocities.com/varcharcode/dragrotatedrop.jpg
    how to make something like that in flash? You drag the
    answer, you rotate it then drop it inside the wheel
    do you have a sample .fla? I know how to make a drag and drop
    but i don't know how to make it rotatable.

    Hi R
    Note that the Border simply adds space to the project so the
    playback controls aren't covering part of your movie. Assuming you
    want that to continue AND have a playback control, you might resize
    the project so the playback control is included in the main movie
    as well as being placed in an area that doesn't possibly obscure
    any screen activity.
    Cheers... Rick

  • Drag and 'no drop'

    I am having difficulty dragging and dropping files. It picks them up... won't let them go. Mac book pro - late 2008. Anybody else having this problem?

    Take a look at System Preferences > Universal Access > Mouse & Trackpad tab > trackpad options.. button > turn drag lock off.  ie Dragging without drag lock.

  • Dragging a jlabel

    hi
    i have JPanel wherin i have n labels
    i need to drag one of the labels to someother location on the panel
    im using java.awt.dnd....and i need to use it cos mouse dragged event is not working properly
    drag n drop action should be Move
    ie when i drag a label it should be removed from the current location n placed in the new location
    and i should have the shadow the label following the drag
    three labels r all different
    i can have as many labels as i want......
    any code references should help
    thanks
    thanks

    any guesses

  • Drag-n-n-drop query joins uses WHERE, not INNER JOIN syntax

    When I highlight a few tables and drag them onto the sql worksheet, it will build a select statement for me and join the tables by their foreign keys.
    That's a nice feature, thanks!
    Three questions. Is it possible to:
    1. get it to use the INNER JOIN and LEFT OUTER JOIN syntax instead of joining the tables in the WHERE clause?
    2. control the table aliases so that it will automatically use the "standard alias" for the table instead of A, B, C, etc.?
    3. get it to not put the schema name into the query?
    Thanks!
    Edited by: David Wendelken on Nov 22, 2008 1:48 PM. Grammar mistake.

    Hi Gopi,
    Your code is Good.
    But try to avoid Inner join with more number of Tables ...because this is a performance issue..
    try to use..
    select (primary key fields mainly,other fields) from LIKP into itab where bolnr in p_bolnr(paramater).
    next try to use for all entries option..
    select (primary key fields mainly,other fields) from VBFA for all entries in itab where (give the condition)....
    simillarly do for the other select ....ok this will try to reduce the performance issue....
    <b><REMOVED BY MODERATOR></b>
    Message was edited by:
            Alvaro Tejada Galindo

  • 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.

  • 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

Maybe you are looking for