0

I have Code where I can move image. Everything works well.

here I have only one ImagePanel (children of JPanel) on the frame.

Questions:

  1. I need to drag and drop image from one JPanel to another JPanel.
  2. Then I need to move dragged image to current panel.

Can you give me an example code, please?

class ImagePanel extends JPanel {
    int x, y;
        BufferedImage image;

        ImagePanel() {
                setBackground(Color.white);
                setSize(450, 400);
                addMouseMotionListener(new MouseMotionHandler());

                Image img = getToolkit().getImage("C:\\2.png");

                MediaTracker mt = new MediaTracker(this);
                mt.addImage(img, 1);
                try {
                        mt.waitForAll();
                } catch (Exception e) {
                        System.out.println("Image not found.");
                }
                image = new BufferedImage(img.getWidth(this), img.getHeight(this),BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2 = image.createGraphics();
                g2.drawImage(img, 0, 0, this);
        }

        public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2D = (Graphics2D) g;
                g2D.drawImage(image, x, y, this);
        }

        class MouseMotionHandler extends MouseMotionAdapter {
                public void mouseDragged(MouseEvent e) {
                        x = e.getX();
                        y = e.getY();
                        repaint();
                }

                public void mouseMoved(MouseEvent e) {
                    
                }
        }
}

I need to do that code, with this following design. I need to add image with some layout (I don't need to done this with Point pixels). or how to add image with some layout? for example Grid bag layout. I don't need Points (x,y). because I need to add another components too.

public class DragAndDrop {
     
    private JFrame frame;        
        /* .. another component here .. */
    
    private JPanel leftPanel;  // here is my image
    public JPanel rightContentPanel; // destination of dragable image

 
    public static void main(String[] args) {              
        DragAndDrop window = new DragAndDrop();
             
    }


    public DragAndDrop() {
        initialize();
    }


    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout(0, 0));
                
        leftPanel = new leftPanel();
        /* add components to left panel */

     
        rightContentPanel =  new rightPanel();
        /* add component to right panel */
        
         
         
        
        frame.getContentPane().add(rightContentPanel, BorderLayout.CENTER);
                frame.getContentPane().add(leftPanel, BorderLayout.WEST);
        
            frame.setVisible(true);
            frame.setResizable(false);
    }
} 

class leftPanel extends JPanel {
    / ... /
}

class rightPanel extends JPanel{
    / ... / 
}
Community
  • 1
  • 1
  • You need to be able to communicate between the two panes, so each one both knows how much of the image they have and be able to monitor the muse movement between them – MadProgrammer May 08 '13 at 10:22
  • can you give me an example, please? –  May 08 '13 at 10:24
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) **Questions:** No, they are specifications. What is your single (specific) *question?* Please don't mistake SO for a coding service or a help desk. – Andrew Thompson May 08 '13 at 11:23
  • Ok. the specific question is that: how to drag and drop image from one panel to another. that's all (there is image on one panel, and there is nothing on another panel. So I need to drag and drop here - from panel, to panel) –  May 08 '13 at 11:28
  • Maybe [this](http://rabbit-hole.blogspot.com.au/2006/05/my-drag-image-is-better-than-yours.html) might help... – MadProgrammer May 08 '13 at 11:29

1 Answers1

2

There's probably any number of ways to achieve what you want. You could use the glass pane or JXLayer or you could stop treating the two panels as separate elements and more like they were just windows into a large virtual space.

This example basically treats the parent component as the "virtual space" into which the two image panes are windows.

They both share the same image and image location details. They, individual, convert the image location (which is in virtual coordinates) to local coordinates and draw as much of the image as would appear on them...

Mouse control is maintained by the parent. This greatly simplifies the process, as it can notify both the panels simultaneously

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class CrossImage {

    public static void main(String[] args) {
        new CrossImage();
    }

    public CrossImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;
        private ImagePane left;
        private ImagePane right;
        private Point imagePoint;

        public TestPane() {
            setBorder(new EmptyBorder(10, 10, 10, 10));
            setLayout(new GridLayout(0, 2, 10, 10));
            left = new ImagePane();
            right = new ImagePane();
            imagePoint = new Point(10, 10);
            left.setImageLocation(imagePoint);
            right.setImageLocation(imagePoint);
            try {
                img = ImageIO.read(new File("Background.jpg"));
                left.setImage(img);
                right.setImage(img);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            add(left);
            add(right);

            MouseAdapter mouseHandler = new MouseAdapter() {
                private Point delta;

                @Override
                public void mousePressed(MouseEvent e) {
                    Point origin = e.getPoint();
                    Rectangle bounds = new Rectangle(imagePoint, new Dimension(img.getWidth(), img.getHeight()));
                    if (bounds.contains(origin)) {
                        delta = new Point(origin.x - imagePoint.x, origin.y - imagePoint.y);
                    }
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (delta != null) {
                        imagePoint = e.getPoint();
                        imagePoint.translate(-delta.x, -delta.y);
                        left.setImageLocation(imagePoint);
                        right.setImageLocation(imagePoint);
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    delta = null;
                }
            };

            addMouseListener(mouseHandler);
            addMouseMotionListener(mouseHandler);
        }
    }

    public class ImagePane extends JPanel {

        private Image image;
        private Point imageLocation;

        public ImagePane() {
            setBorder(new LineBorder(Color.DARK_GRAY));
        }

        @Override
        public Dimension getPreferredSize() {
            return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
        }

        public void setImage(Image image) {
            this.image = image;
            repaint();
        }

        public void setImageLocation(Point imageLocation) {
            this.imageLocation = imageLocation;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (image != null && imageLocation != null) {
                Point p = SwingUtilities.convertPoint(getParent(), imageLocation, this);
                g.drawImage(image, p.x, p.y, this);
            }
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • thank you very much. and now I have another question to you. that's final question. I've just updated my question. I need to add image with some layout (I don't need to done this with Point pixels) how can I do that? please see my question again. –  May 08 '13 at 13:28
  • or how to add image with some layout. for example Grid bag layout. I dont need Point. because I need to add another components too. –  May 08 '13 at 13:51
  • OR, how to add another components in left panel using your code? for example with grid bag layout - I have this problem. –  May 08 '13 at 14:36
  • 1
    To move components from one componet is more complicated, [this](http://rabbit-hole.blogspot.com.au/2006/05/my-drag-image-is-better-than-yours.html) and [this](http://stackoverflow.com/questions/15520610/java-drag-and-drop/15521421#15521421) and [this](http://stackoverflow.com/questions/13855184/drag-and-drop-custom-object-from-jlist-into-jlabel/13856193#13856193) and [this](http://stackoverflow.com/questions/11201734/java-how-to-drag-and-drop-jpanel-with-its-components/11443501#11443501) might help – MadProgrammer May 08 '13 at 20:37
  • MadProgrammer. Can you change [this code](http://stackoverflow.com/questions/15520610/java-drag-and-drop/15521421#15521421) (it's your code) so that after dropping, I want to move it. could you help me, please? p.s I want images left instead of text. thank you :-) –  May 10 '13 at 08:25
  • MadProgrammer. Please see. [This question](http://stackoverflow.com/questions/16478413/move-component-after-drag-and-drop)( reference of question) –  May 10 '13 at 09:22
  • +1 nice. Also see [this](http://stackoverflow.com/a/17359895/1133011) answer for using inbuilt DnD support of Swing and its components to move Image from one panel to another. And its [variation](http://stackoverflow.com/questions/14273923/how-can-i-set-the-priority-mouse-listener/14276466#14276466) which allows Drag and Drop of Swing components. – David Kroukamp Jun 28 '13 at 08:16