JLabel & dragging

If I have a JPanel with BorderLayout, it is possible to dynamically add JLabel (with IconImages) to this panel and be able to drag them around in different positions?  Do I have to change the JPanel to a null layout?  

Could someone provide a small snipet or even explain the method used to achieve this effect.

Thanks,
David
lomidienAsked:
Who is Participating?
 
doronbConnect With a Mentor Commented:
Here is a Drag and Drop example:
____________________________
// Main Class..
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
package dragdrop;

import java.awt.*;
import javax.swing.*;

public class Application {
      private boolean packFrame = false;
      //Construct the application
      public Application() {
            TestFrame frame = new TestFrame();
            //Validate frames that have preset sizes
            //Pack frames that have useful preferred size info, e.g. from their layout
            if (packFrame) {
                  frame.pack();
            } else {
                  frame.validate();
            }
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = frame.getSize();
            if (frameSize.height > screenSize.height) {
                  frameSize.height = screenSize.height;
            }
            if (frameSize.width > screenSize.width) {
                  frameSize.width = screenSize.width;
            }
            frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
            frame.setVisible(true);
      }

      //Main method
      public static void main(String[] args) {
            try {
                  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                  e.printStackTrace();
            }
            new Application();
      }
}
____________________________
// Test Frame..
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
package dragdrop;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestFrame extends JFrame {
      private JPanel contentPane;
      private JMenuBar jMenuBar1 = new JMenuBar();
      private JMenu jMenuFile = new JMenu();
      private JMenuItem jMenuFileExit = new JMenuItem();
      private JMenu jMenuHelp = new JMenu();
      private JMenuItem jMenuHelpAbout = new JMenuItem();
      private BorderLayout borderLayout1 = new BorderLayout();
      private JPanel ddc = new DragDropContainer();
      private JTextField jTextField1 = new JTextField();
      //Construct the frame
      public TestFrame() {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            try {
                  jbInit();
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

      //Component initialization
      private void jbInit() throws Exception {
            contentPane = (JPanel)this.getContentPane();
            contentPane.setLayout(borderLayout1);
            this.setSize(new Dimension(640, 480));
            this.setTitle("Frame Title");
            jMenuFile.setText("File");
            jMenuFileExit.setText("Exit");
            jMenuFileExit.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        jMenuFileExit_actionPerformed(e);
                  }
            });
            jMenuHelp.setText("Help");
            jMenuHelpAbout.setText("About");
            jMenuHelpAbout.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        jMenuHelpAbout_actionPerformed(e);
                  }
            });
            ddc.setLayout(null);
            jTextField1.setBounds(new Rectangle(258, 143, 100, 16));
            jMenuFile.add(jMenuFileExit);
            jMenuHelp.add(jMenuHelpAbout);
            jMenuBar1.add(jMenuFile);
            jMenuBar1.add(jMenuHelp);
            contentPane.add(ddc, BorderLayout.CENTER);
            ddc.add(jTextField1, null);
            this.setJMenuBar(jMenuBar1);
      }

      //File | Exit action performed
      public void jMenuFileExit_actionPerformed(ActionEvent e) {
            System.exit(0);
      }

      //Help | About action performed
      public void jMenuHelpAbout_actionPerformed(ActionEvent e) {
      }

      //Overridden so we can exit when window is closed
      protected void processWindowEvent(WindowEvent e) {
            super.processWindowEvent(e);
            if (e.getID() == WindowEvent.WINDOW_CLOSING) {
                  jMenuFileExit_actionPerformed(null);
            }
      }
}
____________________________
// JPanel for Drag and Drop GUI..
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
package dragdrop;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class DragDropContainer extends JPanel {
      // The component we will drag across this Container..
      private Component dragee;
      // The rectangle used for dragging..
      private Rectangle dragRect;
      // The delta between where the user clicked to start dragging and the location of the dragged component..
      private Point delta;

      // Create a mousePressed and mouseReleased events handler..
      private MouseAdapter ma = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                  // First, get the Component the user intends to drag..
                  dragee = (Component)e.getSource();
                  // Should the Component be dragged?
                  if (e.getButton() == MouseEvent.BUTTON1 && e.isControlDown() && dragee != DragDropContainer.this) {
                        // Next, get the bounding rectangle of the dragged component..
                        dragRect = dragee.getBounds();
                        delta = dragee.getLocation();
                        delta.translate(-e.getX(), -e.getY());
                        // Repaint the whole thing..
                        repaint();
                  } else {
                        dragee = null;
                  }
            }
            public void mouseReleased(MouseEvent e) {
                  if (dragee == e.getSource()) {
                        // Move the dragged component to its new location..
                        dragee.setBounds(dragRect);
                        // Nullify both rectangle and dragged component data-members..
                        dragRect = null;
                        dragee = null;
                        // Now, repaint again..
                        repaint();
                  }
            }
      };

      // Add the mouseDragged event handler..
      private MouseMotionAdapter mma = new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                  // Are we currently dragging anything?
                  if (dragRect != null) {
                        // Update the location of the dragging rectangle..
                        dragRect.setLocation(e.getPoint());
                        // Move rectangle so that it surrounds the mouse pointer as when first clicked..
                        dragRect.translate(delta.x, delta.y);
                        // Make sure the user can't drag the component out of the container..
                        if (dragRect.x < 0) {
                              dragRect.x = 0;
                        }
                        if (dragRect.y < 0) {
                              dragRect.y = 0;
                        }
                        if (dragRect.x + dragRect.width > getWidth()) {
                              dragRect.x = getWidth() - dragRect.width;
                        }
                        if (dragRect.y + dragRect.height > getHeight()) {
                              dragRect.y = getHeight() - dragRect.height;
                        }
                        // Repaint!
                        repaint();
                  }
            }
      };

      public void remove(int index) {
            // Find the Component..
            Component comp = getComponent(index);
            // Remove the mouse event handlers..
            comp.removeMouseListener(ma);
            comp.removeMouseMotionListener(mma);
            // Remove the component..
            super.remove(index);
      }

      protected void addImpl(Component comp, Object constraints, int index) {
            // Add the mouse event handlers..
            comp.addMouseListener(ma);
            comp.addMouseMotionListener(mma);
            // Add the component..
            super.addImpl(comp, constraints, index);
      }

      public void paint(Graphics g) {
            // Paint everything..
            super.paint(g);
            // Are we dragging anything now?
            if (dragRect != null) {
                  // Draw the dragging rectangle..
                  g.drawRect(dragRect.x, dragRect.y, dragRect.width, dragRect.height);
            }
      }
}

If you copy and paste each segment into its own Java source file, then compile everything and run dragdrop.Application, you will see a TextField in a window.  Once you click the Left Mouse Button while holding down the Ctrl button to drag the TextField around.  This DragDropContainer panel enables drag&drop functionality for ANY other GUI component you add into it, so adding a JLabel to it instead of a JTextField will let you drag the Label around.

Good luck :)
0
 
CEHJCommented:
>>Do I have to change the JPanel to a null layout?  

Yes:

http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html#label
0
 
CEHJCommented:
Sorry - that examples not what i thought. Basically you need to add a MouseMotionListener to the label's parent and move it while the button is down and stop when it's up (with a null layout)
0
 
CEHJCommented:
Have a look at the example here:

http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

It shows a JLabel being moved. You need to reverse the functionality, since this moves the label when dragging is *not* occurring
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.