如何在Java GUI中使用鼠标光标拖动图像?

时间:2015-01-13 05:05:39

标签: java image user-interface drag imageicon

//我的代码调用目录中的n个图像放在JPanel上

 public void imageAdder(int n, String name){
    BufferedImage myPic = null;
    for (int i = 0; i <= n; i++){
        try {
        myPic = ImageIO.read(new File("Images/" + name + i + ".jpg"));
        } catch (Exception e){
        System.out.println("no file man cmon");
        }
        JLabel picLabel = new JLabel(new ImageIcon(myPic));
      //  picLabel.setBounds(mouseX, mouseY, 100, 50);
      //  picLabel.addMouseMotionListener(this);
      //  picLabel.addMouseListener(this);
        canvas.add(picLabel);
    }}

我读到了类DragSource以及如何使用拖动类型图像的方法,但我不确定这是否适用于我的代码。如果我想用鼠标自由拖动图像,我该怎么办?

2 个答案:

答案 0 :(得分:2)

您可以通过多种方式实现此目标......例如,您可以使用自定义绘画自行绘制单个图像。每次按下/拖动鼠标时,您都需要计算拖动的图像。

稍微简单的解决方案可能是使用JLayeredPane并继续使用JLabel来呈现图片,然后您可以使用MouseListenerMouseMoitionListener来检测按下和/或拖动标签并相应地更新它的位置......

有关详细信息,请参阅How to Write a Mouse ListenerHow to Use Layered Panes

Drag

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestDrag {

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

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

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

    public class TestPane extends JLayeredPane {

        public TestPane() {
            File[] images = new File("C:\\hold\\thumbnails").listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName().toLowerCase();
                    return name.endsWith(".png") || 
                                    name.endsWith(".jpg") || 
                                    name.endsWith(".bmp") ||
                                    name.endsWith(".gif");
                }
            });

            int x = 0;
            int y = 0;
            for (File imgFile : images) {

                try {
                    BufferedImage img = ImageIO.read(imgFile);
                    JLabel label = new JLabel(new ImageIcon(img));
                    label.setSize(label.getPreferredSize());
                    label.setLocation(x, y);
                    MouseHandler mh  = new MouseHandler();
                    label.addMouseListener(mh);
                    label.addMouseMotionListener(mh);
                    add(label);
                    x += 20;
                    y += 20;
                } catch (IOException exp) {
                    exp.printStackTrace();
                }

            }

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 800);
        }

        public class MouseHandler extends MouseAdapter {

            private Point offset;

            @Override
            public void mousePressed(MouseEvent e) {
                JLabel label = (JLabel) e.getComponent();
                moveToFront(label);
                offset = e.getPoint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                int x = e.getPoint().x - offset.x;
                int y = e.getPoint().y - offset.y;
                Component component = e.getComponent();
                Point location = component.getLocation();
                location.x += x;
                location.y += y;
                component.setLocation(location);
            }

        }

    }

}

答案 1 :(得分:0)

查看Java Swing中的自定义类,可能有用的链接可以帮助您入门:

Java2s - DragandDropSupportforImages

Drag Drop Image Screenshot

DragImage.java DropImage.java DragImageEvent.java