java - 拖放图像

标签 java image swing jpanel drag-and-drop

我正在制作一个用 Java 编辑图像的程序。我想知道是否可以将图像从用户桌面拖到 JPanel 上,然后将被拖动的图像设置为 JPanel 的背景。这在Java中可能吗?如果可以,我该怎么做?

最佳答案

简短的回答是:是的,这是可能的。

有几种方法可以做到这一点,我将为您提供最简单的一种代码:将图像文件从某处拖到您的 Swing 应用程序中。但是,您也可以从图像编辑器将图像复制到剪贴板并将其粘贴到那里,但我认为您不需要这样做。要实现第二个用例,您必须使用 DataFlavor.imageFlavor 而不是我的示例向您展示的 DataFlavor.javaFileListFlavor。因此,要测试下面的代码,只需将 MainPanel 的实例添加到容器中,然后在应用运行时将图像文件拖到面板中。

这是 TransferHandler 的实现:

import java.awt.Cursor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

public class ImageTransferHandler extends TransferHandler {
    private static final DataFlavor FILE_FLAVOR = DataFlavor.javaFileListFlavor;

    private MainPanel mainPanel;

    public ImageTransferHandler(MainPanel panel) {
        mainPanel = panel;
    }

    /**
     * The method to handle the transfer between the source of data and the
     * destination, which is in our case the main panel.
     */
    public boolean importData(JComponent c, Transferable t) {
        if (canImport(c, t.getTransferDataFlavors())) {
            if (transferFlavor(t.getTransferDataFlavors(), FILE_FLAVOR)) {
                try {
                    List<File> fileList = (List<File>) t.getTransferData(FILE_FLAVOR);
                    if (fileList != null && fileList.toArray() instanceof File[]) {
                        File[] files = (File[]) fileList.toArray();
                        mainPanel.addFiles(files);
                    }
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (UnsupportedFlavorException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * Returns the type of transfer actions to be supported.
     */
    public int getSourceActions(JComponent c) {
        return COPY_OR_MOVE;
    }

    /**
     * Specifies the actions to be performed after the data has been exported.
     */
    protected void exportDone(JComponent c, Transferable data, int action) {
        c.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    /**
     * Returns true if the specified flavor is contained in the flavors array,
     * false otherwise.
     */
    private boolean transferFlavor(DataFlavor[] flavors, DataFlavor flavor) {
        boolean found = false;
        for (int i = 0; i < flavors.length && !found; i++) {
            found = flavors[i].equals(flavor);
        }
        return found;
    }

    /**
     * Returns true if the component can import the specified flavours, false
     * otherwise.
     */
    public boolean canImport(JComponent c, DataFlavor[] flavors) {
        for (int i = 0; i < flavors.length; i++) {
            if (FILE_FLAVOR.equals(flavors[i])) {
                return true;
            }
        }
        return false;
    }
}

这是我要添加 TransferHandler 并将图像绘制为背景的面板:

public class MainPanel extends JPanel {
    private Image image;

    MainPanel() {
        setTransferHandler(new ImageTransferHandler(this));
    }

    void addFiles(File[] files) {
        for (File file : files) {
            try {
                image = ImageIO.read(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (image != null) {
            repaint();
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        int width = getWidth();
        int height = getHeight();
        drawImage((Graphics2D) g, width, height);
    }

    private void drawImage(Graphics2D g2, int width, int height) {
        if (image != null) {
            g2.drawImage(image, 0, 0, width, height, null);
        } else {
            g2.drawRect(10, 10, width - 20, height - 20);
        }
    }
}

关于java - 拖放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443758/

相关文章:

java - 如何在 Java 中更改不可编辑的 JTextPane 的背景颜色?

java - 制作两个选项窗口的最佳方法是什么?

java - 为什么Character.toString((char)i)在某个地方不起作用

java - 什么更有效率 : read in file from java or shell script?

c - 使用C编程将图像存储在“二进制”数组中

css - rails : Is it better to display images with image_tag or css background image?

javascript - 我如何才能使外部文件中的 javascript 仅适用于 PHP 文件内的 div 中的图像?

java - java 中的十进制到二进制 - 我的代码有什么问题?

java - Tomcat 5.5 : The requested resource is not available

java - 将一个 JPanel 添加到另一个 JPanel 会添加填充