Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8219675
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T13:15:30+00:00 2026-06-07T13:15:30+00:00

I am using a TransferHandler to pass data from a JPanel to a JTextArea

  • 0

I am using a TransferHandler to pass data from a JPanel to a JTextArea as a JLabel (Click somewhere in the left panel to create the JLabel to drag)

The transfer of the data works fine, but I’d like to also “show” the JLabel as its being dragged along with the mouse pointer.

If you comment out

dropLabel.setTransferHandler(new TransferHandler("text"));

dropLabel.getTransferHandler().exportAsDrag(dropLabel, e,
            TransferHandler.COPY);

you will see how I want it to look. (but of course then the data won’t be transferred).

How can I get both the transfer to work and the JLabel to follow the mouse cursor?

Here is the code:

import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.Border;

public class DragTest extends JFrame implements MouseMotionListener,
        MouseListener {

    private JPanel leftPanel = new JPanel(null);
    private JPanel rightPanel = new JPanel(null);
    private JLabel dragLabel = new JLabel("drop");
    private final JWindow window = new JWindow();
    JLabel dropLabel;

    public DragTest() {
        this.setLayout(new GridLayout(1, 2));

        leftPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        rightPanel.setBorder(BorderFactory.createLineBorder(Color.black));
        this.add(leftPanel);
        this.add(rightPanel);
        leftPanel.addMouseListener(this);
        leftPanel.addMouseMotionListener(this);

        JTextArea area = new JTextArea();

        rightPanel.setLayout(new GridLayout(1, 1));
        rightPanel.add(area);

        dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
    }

    @Override
    public void mousePressed(MouseEvent e) {

        dropLabel = new JLabel("drop");

        Dimension labelSize = dropLabel.getPreferredSize();
        dropLabel.setSize(labelSize);
        int x = e.getX() - labelSize.width / 2;
        int y = e.getY() - labelSize.height / 2;
        dropLabel.setLocation(x, y);
        leftPanel.add(dropLabel);

        dropLabel.setTransferHandler(new TransferHandler("text"));

        dropLabel.getTransferHandler().exportAsDrag(dropLabel, e,
                TransferHandler.COPY);

        repaint();

    }

    @Override
    public void mouseDragged(MouseEvent me) {
        dragLabel = new JLabel("drop");
        dragLabel.setFont(new Font("Serif", Font.BOLD, 48));
        int x = me.getPoint().x;
        int y = me.getPoint().y;
        window.add(dragLabel);
        window.pack();
        Point pt = new Point(x, y);
        Component c = (Component) me.getSource();
        SwingUtilities.convertPointToScreen(pt, c);
        window.setLocation(pt);
        window.setVisible(true);
        repaint();
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }

    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

//      leftPanel.remove(dropLabel);

        window.remove(dragLabel);
        window.setVisible(false);

        repaint();
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    public static void main(String[] args) {

        DragTest frame = new DragTest();
        frame.setVisible(true);
        frame.setSize(600, 400);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T13:15:31+00:00Added an answer on June 7, 2026 at 1:15 pm

    Another example:

    enter image description here

    Edit: Fix a blinking cursor

    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.activation.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class DragTest3 {
      public JComponent makeUI() {
        DragPanel p1 = new DragPanel();
        p1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        p1.add(new JLabel(UIManager.getIcon("OptionPane.warningIcon")));
        p1.add(new JLabel(UIManager.getIcon("OptionPane.errorIcon")));
        p1.add(new JLabel("Label1"));
        p1.add(new JLabel("Label2"));
        MouseListener handler = new Handler();
        p1.addMouseListener(handler);
        LabelTransferHandler th = new LabelTransferHandler();
        p1.setTransferHandler(th);
        JPanel p = new JPanel(new GridLayout(1,2));
        p.add(p1);
    
        DragPanel p2 = new DragPanel();
        p2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        p2.addMouseListener(handler);
        p2.setTransferHandler(th);
        p.add(p2);
    
        JPanel panel = new JPanel(new GridLayout(2,1));
        panel.add(p);
        panel.add(new JScrollPane(new JTextArea()));
        return panel;
      }
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() {
            createAndShowGUI();
          }
        });
      }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new DragTest3().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    }
    class DragPanel extends JPanel {
      public DragPanel() {
        super();
      }
      public JLabel draggingLabel;
    }
    class Handler extends MouseAdapter {
      @Override public void mousePressed(MouseEvent e) {
        DragPanel p = (DragPanel)e.getSource();
        Component c = SwingUtilities.getDeepestComponentAt(p, e.getX(), e.getY());
        if(c!=null && c instanceof JLabel) {
          p.draggingLabel = (JLabel)c;
          p.getTransferHandler().exportAsDrag(p, e, TransferHandler.MOVE);
        }
      }
    }
    class LabelTransferHandler extends TransferHandler {
      private final DataFlavor localObjectFlavor;
      private final JLabel label = new JLabel() {
        @Override public boolean contains(int x, int y) {
          return false;
        }
      };
      private final JWindow window = new JWindow();
      public LabelTransferHandler() {
        System.out.println("LabelTransferHandler");
        localObjectFlavor = new ActivationDataFlavor(
          DragPanel.class, DataFlavor.javaJVMLocalObjectMimeType, "JLabel");
        window.add(label);
        window.setAlwaysOnTop(true);
        window.setBackground(new Color(0,true));
        DragSource.getDefaultDragSource().addDragSourceMotionListener(
        new DragSourceMotionListener() {
          @Override public void dragMouseMoved(DragSourceDragEvent dsde) {
            Point pt = dsde.getLocation();
            pt.translate(5, 5); // offset
            window.setLocation(pt);
          }
        });
      }
      @Override protected Transferable createTransferable(JComponent c) {
        System.out.println("createTransferable");
        DragPanel p = (DragPanel)c;
        JLabel l = p.draggingLabel;
        String text = l.getText();
        //TEST
        //if(text==null) {
        //    text = l.getIcon().toString();
        //}
        //return new StringSelection(text+"\n");
        final DataHandler dh = new DataHandler(c, localObjectFlavor.getMimeType());
        if(text==null) return dh;
        final StringSelection ss = new StringSelection(text+"\n");
        return new Transferable() {
          @Override public DataFlavor[] getTransferDataFlavors() {
            ArrayList<DataFlavor> list = new ArrayList<>();
            for(DataFlavor f:ss.getTransferDataFlavors()) {
              list.add(f);
            }
            for(DataFlavor f:dh.getTransferDataFlavors()) {
              list.add(f);
            }
            return list.toArray(dh.getTransferDataFlavors());
          }
          public boolean isDataFlavorSupported(DataFlavor flavor) {
            for (DataFlavor f: getTransferDataFlavors()) {
              if (flavor.equals(f)) {
                return true;
              }
            }
            return false;
          }
          public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if(flavor.equals(localObjectFlavor)) {
              return dh.getTransferData(flavor);
            } else {
              return ss.getTransferData(flavor);
            }
          }
        };
      }
      @Override public boolean canImport(TransferSupport support) {
        if(!support.isDrop()) {
          return false;
        }
        return true;
      }
      @Override public int getSourceActions(JComponent c) {
        System.out.println("getSourceActions");
        DragPanel p = (DragPanel)c;
        label.setIcon(p.draggingLabel.getIcon());
        label.setText(p.draggingLabel.getText());
        window.pack();
        Point pt = p.draggingLabel.getLocation();
        SwingUtilities.convertPointToScreen(pt, p);
        window.setLocation(pt);
        window.setVisible(true);
        return MOVE;
      }
      @Override public boolean importData(TransferSupport support) {
        System.out.println("importData");
        if(!canImport(support)) return false;
        DragPanel target = (DragPanel)support.getComponent();
        try {
          DragPanel src = (DragPanel)support.getTransferable().getTransferData(localObjectFlavor);
          JLabel l = new JLabel();
          l.setIcon(src.draggingLabel.getIcon());
          l.setText(src.draggingLabel.getText());
          target.add(l);
          target.revalidate();
          return true;
        } catch(UnsupportedFlavorException ufe) {
          ufe.printStackTrace();
        } catch(java.io.IOException ioe) {
          ioe.printStackTrace();
        }
        return false;
      }
      @Override protected void exportDone(JComponent c, Transferable data, int action) {
        System.out.println("exportDone");
        DragPanel src = (DragPanel)c;
        if(action == TransferHandler.MOVE) {
          src.remove(src.draggingLabel);
          src.revalidate();
          src.repaint();
        }
        src.draggingLabel = null;
        window.setVisible(false);
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using mercurial, I've run into an odd problem where a line from one committer
Using Android TelephonyManager an application can obtain the state of data activity over the
Using php/html, I want to retrieve email addresses (plus other information) from MySQL and
Using Core Data, I have a fetch request to fetch the minimum of a
(Using MVC 2) From inside my controller action, I need to display the url:
Using Jenkins or Hudson I would like to create a pipeline of builds with
Using Java,I have to fetch multiple sets of values from an XML file to
Using Entity Framework CodeFirst, how do I create a created datetime column that gets
Using Github's Issue Tracker, how can one create an issue tied to an organization
Using the http://www.ifans.com/forums/showthread.php?t=132024 post from another question i am allowing the user to enter

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.