[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

JLabel & dragging

Posted on 2005-04-22
4
Medium Priority
?
794 Views
Last Modified: 2013-11-23
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
0
Comment
Question by:lomidien
  • 3
4 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 13845694
>>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
 
LVL 86

Expert Comment

by:CEHJ
ID: 13845717
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
 
LVL 9

Accepted Solution

by:
doronb earned 2000 total points
ID: 13853371
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 13854691
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

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month20 days, 8 hours left to enroll

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question