我已经在两个JPanel之间实现了这种非常基本的拖放操作,但这并不能真正满足我的要求!
public class test extends JFrame { { JPanel mainpanel, storypanel, imageselect; public test(){ mainpanel = new JPanel(new BorderLayout()); storypanel = new JPanel(); imageselect = new JPanel(); MouseListener listener = new MouseAdapter(){ public void mousePressed(MouseEvent e) { JComponent c = (JComponent) e.getSource(); TransferHandler handler = c.getTransferHandler(); handler.exportAsDrag(c, e, TransferHandler.COPY); } }; int j = 0; BufferedImage myImages; JLabel imgselect = new JLabel(); try { myImages = ImageIO.read(new File("four.jpg")); //myImages[j] = resize(myImages[j]); imgselect= new JLabel(new ImageIcon(myImages)); System.out.println(j); imageselect.add(imgselect); imgselect.addMouseListener(listener); imgselect.setTransferHandler(new TransferHandler("icon")); } catch(Exception e) {}; int i = 0; BufferedImage storyimages; JLabel storylabel = new JLabel(); //targetImg = new ImageIcon("lmkpackage/base/TargetImg.jpg"); try{ storyimages = ImageIO.read(new File("TargetImg.jpg")); //storyimages[i] = resize(storyimages[i]); storylabel = new JLabel(new ImageIcon(storyimages)); System.out.println(i); storypanel.add(storylabel); storylabel.addMouseListener(listener); storylabel.setTransferHandler(new TransferHandler("icon")); } catch(Exception e) {}; mainpanel.add(imageselect, BorderLayout.NORTH); mainpanel.add(storypanel, BorderLayout.SOUTH); getContentPane().add(mainpanel); } public static void main(String[] args){ System.out.println("Application Running"); JFrame mainframe = new test(); mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.setSize(1000,1000); mainframe.setVisible(true); } }
对不起,我在这里不太清楚。我试图将ImageIcon从imageselect面板上的JLabel拖动到故事情节面板上的另一个JLabel。我可以使用上面的代码来做到这一点。但是,当我这样做时,可以从imageselect面板中拖动一个ImageIcon,然后在同一面板上替换另一个ImageIcon。我不希望这种情况发生。我也可以从故事情节面板拖到不需要的图像选择面板。
我并不是要成为傻瓜式的代码,我只是在寻找正确的方向!
编辑:我想知道有什么方法可以计算成功的拖放操作,下面的解决方案回答了我的原始问题。
这基本上是@Andrew的评论的概述-由于您的SSCCE,很容易实现:-)
子类TransferHandler,重写canImport以检查源标签是否在imageSelect面板上,如果不是,则拒绝。
// custom transferHandler which decides about imports based on source TransferHandler handler = new TransferHandler("icon") { @Override public boolean canImport(TransferSupport support) { return super.canImport(support) && support.getComponent().getParent() != imageSelectPanel; } }; // use the handler on all labels (handlers can be shared, btw) // for each label on imageSelectPanel imageSelectLabel.setTransferHandler(handler) // for each label on the target panel (aka storyPanel) storyLabel.setTransferHandler(handler)