简体   繁体   中英

move image from one panel to another

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{
    / ... / 
}

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

在此输入图像描述

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);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM