拖动两个图像并将它们放在同一个JFrame

时间:2016-04-12 11:29:45

标签: java swing drag-and-drop

我有一个代码,我必须从我的桌面拖动两个图像并将其放在一个框架中的两个可拖动按钮中。按钮已经在框架上制作。但是在拖动图像时,它们只能拖动到一个按钮。图像不会被拖到另一个图像上。我创建了一个DragListener类,其中拖动方法占主导地位,主类DragInitialListener我已经传递了类DragButton的对象,因此创建了两个可拖动的按钮。我已经尝试了我能想到的一切,制作了两个DragListener类,以不同的方式传递了方法,但只能在一个按钮中拖动图像。我希望这两个按钮都能够保存图像。请帮帮我。这是我到目前为止所做的代码:

//这是主要的课程

public class DragInitialListener  extends javax.swing.JFrame {

private volatile int draggedAtX, draggedAtY;

public DragInitialListener() {

initComponents();
Droptargets();
Droptarget();
}

public void Droptarget()
{

DragListener d;
DragButton db = new DragButton();
db.setSize(170,140);
d= new DragListener(db);

DropTarget drop = new DropTarget(this,d);


this.getContentPane().add(db);
}

 public void Droptargets()
{

   DragListener dd;
    DragButton db1 = new DragButton();
   db1.setSize(170,140);


    dd= new DragListener(db1);

    DropTarget drop1 = new DropTarget(this,dd);



    this.getContentPane().add(db1);



   }

// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        


 public static void main(String args[]) {


    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {

            new DragInitialListener().setVisible(true);

        }
    });
  }

// Variables declaration - do not modify                     
// End of variables declaration                   

   }

//这是DragListener类

    public class DragListener extends JButton implements DropTargetListener     
    {

     JButton imagebutton = new JButton();
     //  JButton imagebutton1 = new JButton();

     private volatile int draggedAtX, draggedAtY;


      DragListener(JButton image) {

       imagebutton=image;

        }


         @Override
         public void dragEnter(DropTargetDragEvent dtde) {

          }

          @Override
           public void dragOver(DropTargetDragEvent dtde) {

            }

           @Override
            public void dropActionChanged(DropTargetDragEvent dtde) {


             }

            @Override
             public void dragExit(DropTargetEvent dte) {

             }

             @Override
             public void drop(DropTargetDropEvent ev) {

              ev.acceptDrop(DnDConstants.ACTION_COPY);
              Transferable t = ev.getTransferable();
               //DropTarget test = (DropTarget) ev.getSource();

                DataFlavor[] df= t.getTransferDataFlavors();
                 for(DataFlavor f:df)
               {
                try
                 {
                  if(f.isFlavorJavaFileListType())
                  {
                   List<File> files =(List<File>) t.getTransferData(f);

                    for(File file : files)
                     {
                       displayImage(file.getPath());
                        }
                      }
                       }
                       catch(Exception ex)
                          {
                           JOptionPane.showMessageDialog(null, ex);
                           }
                            }
                              }
                          private void displayImage(String path)
                         {
                         BufferedImage img = null;
                          try
                         {
                          img =ImageIO.read(new File(path));

                            }
                            catch(Exception e)
                            {

                              }
                            ImageIcon icon = new ImageIcon(img);
                            imagebutton.setIcon(icon);


                                  }



                               }

1 个答案:

答案 0 :(得分:1)

开始简单,让一个按钮工作,如果你可以让一个工作,你可以得到100工作

这是一个非常简单的例子,它使用了传输API,因为你真的只关心丢弃而不是拖动

Drop Pony

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        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 JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            JButton btn = new JButton("Drop here");
            btn.setVerticalTextPosition(JButton.BOTTOM);
            btn.setHorizontalTextPosition(JButton.CENTER);
            btn.setTransferHandler(new ImageTransferHandler());
            add(btn);
        }

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

    }

    public static class ImageTransferHandler extends TransferHandler {

        public static final DataFlavor[] SUPPORTED_DATA_FLAVORS = new DataFlavor[]{
            DataFlavor.javaFileListFlavor,
            DataFlavor.imageFlavor
        };

        @Override
        public boolean canImport(TransferHandler.TransferSupport support) {
            boolean canImport = false;
            for (DataFlavor flavor : SUPPORTED_DATA_FLAVORS) {
                if (support.isDataFlavorSupported(flavor)) {
                    canImport = true;
                    break;
                }
            }
            return canImport;
        }

        @Override
        public boolean importData(TransferHandler.TransferSupport support) {
            boolean accept = false;
            if (canImport(support)) {
                try {
                    Transferable t = support.getTransferable();
                    Component component = support.getComponent();
                    if (component instanceof JButton) {
                        Image image = null;
                        if (support.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                            image = (Image) t.getTransferData(DataFlavor.imageFlavor);
                        } else if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                            if (files.size() > 0) {
                                image = ImageIO.read((File) files.get(0));
                            }
                        }
                        ImageIcon icon = null;
                        if (image != null) {
                            icon = new ImageIcon(image);
                        }
                        ((JButton) component).setIcon(icon);
                        accept = true;
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
            return accept;
        }
    }
}

因此,只需更改布局并使用

复制按钮即可
public TestPane() {
    setLayout(new GridLayout(5, 5));
    for (int index = 0; index < 5 * 5; index++) {
        JButton btn = new JButton("Drop here");
        btn.setVerticalTextPosition(JButton.BOTTOM);
        btn.setHorizontalTextPosition(JButton.CENTER);
        btn.setTransferHandler(new ImageTransferHandler());
        add(btn);
    }
}

我能够实现......

Multiple drops

更新...

显然,我可能误解了这个问题,而不是第一次。根据我的解释,你可能想要拖动多个图像并将它们应用到按钮上。令人惊讶的是,这个过程并没有太大改变。

在此示例中,我已将TransferHandler应用于JPanel而不是按钮,并为其提供了我想要更新的按钮。您可以轻松更新此按钮以获得可变数量的按钮,但我已经开始使用两个按钮。

Drag Multiple Images

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        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 JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());

            JButton left = makeButton("Left");
            JButton right = makeButton("Right");

            add(left);
            add(right);

            setTransferHandler(new ImageTransferHandler(left, right));
        }

        protected JButton makeButton(String text) {
            JButton btn = new JButton(text);
            btn.setVerticalTextPosition(JButton.BOTTOM);
            btn.setHorizontalTextPosition(JButton.CENTER);
            return btn;
        }

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

    }

    public static class ImageTransferHandler extends TransferHandler {

        public static final DataFlavor[] SUPPORTED_DATA_FLAVORS = new DataFlavor[]{
            DataFlavor.javaFileListFlavor,};

        private JButton left, right;

        public ImageTransferHandler(JButton left, JButton right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public boolean canImport(TransferHandler.TransferSupport support) {
            boolean canImport = false;
            for (DataFlavor flavor : SUPPORTED_DATA_FLAVORS) {
                if (support.isDataFlavorSupported(flavor)) {
                    canImport = true;
                    break;
                }
            }
            return canImport;
        }

        @Override
        public boolean importData(TransferHandler.TransferSupport support) {
            boolean accept = false;
            if (canImport(support)) {
                try {
                    Transferable t = support.getTransferable();
                    Image image = null;
                    if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                        List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                        JButton buttons[] = new JButton[]{left, right};
                        for (int index = 0; index < Math.min(files.size(), 2); index++) {
                            if (files.size() > 0) {
                                image = ImageIO.read((File) files.get(index));
                                ImageIcon icon = null;
                                if (image != null) {
                                    icon = new ImageIcon(image);
                                }
                                buttons[index].setIcon(icon);
                            }
                        }
                        accept = true;
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
            return accept;
        }
    }
}

现在,您需要自己定义规则,例如,当用户仅拖动单个图像时会发生什么?你每次都把它应用到第一个按钮(就像我有的那样),或者你是否尝试找到没有图像的按钮并更新它?如果所有按钮都有图像会怎么样?它到底在哪里?

你是否拒绝超过2张图片的拖拽?