如何通过拖放TransferHandler“粘贴”?

时间:2011-12-05 13:59:42

标签: java drag-and-drop

enter image description here我有这个: 并希望图像SD能够被拖放到另一个JLabel(JLabel现在显示图片SD),我该怎么做?

    ImageIcon SD = new ImageIcon("resources/terrains/StoneDungeon.jpg");
    JLabel dns=new JLabel( SD);
    frame.getContentPane().add(dns);
    dns.setBounds(800,150,50,50);
    dns.setFont(new Font("Courior", Font.BOLD, 25));
    dns.setForeground(Color.red);
    final String propertyName = "text";
    dns.setTransferHandler(new TransferHandler(propertyName));
    // Listen for mouse clicks
    dns.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent evt) {
            JComponent comp = (JComponent)evt.getSource();
            TransferHandler th = comp.getTransferHandler();


            // Start the drag operation
            th.exportAsDrag(comp, evt, TransferHandler.COPY);

请不要告诉我看看教程,我已经有了。

我没有足够的代表来回答我的问题,所以答案是:

那是愚蠢的错误!!!!!!!!

代码应该是:

        ImageIcon SD = new ImageIcon("resources/terrains/StoneDungeon.jpg");
    JLabel dns=new JLabel( SD);
    frame.getContentPane().add(dns);
    dns.setBounds(800,150,50,50);
    dns.setFont(new Font("Courior", Font.BOLD, 25));
    dns.setForeground(Color.red);
    dns.setTransferHandler(new TransferHandler(SD));
    MouseListener ml = new MouseAdapter(){
        public void mousePressed(MouseEvent e){
            JComponent jc = (JComponent)e.getSource();
            TransferHandler th = jc.getTransferHandler();
            th.exportAsDrag(jc, e, TransferHandler.COPY);
        }
    };
    dns.addMouseListener(ml);

我已经放了一些字符串变量而不是要移动的图片! 但现在的问题是,你不能拖放图标(SD)

1 个答案:

答案 0 :(得分:0)

ImageIcon SD = new ImageIcon("resources/terrains/StoneDungeon.jpg");
JLabel dns=new JLabel( SD);
    frame.getContentPane().add(dns);
    dns.setBounds(800,150,50,50);
    dns.setFont(new Font("Courior", Font.BOLD, 25));
    dns.setForeground(Color.red);
    dns.setTransferHandler(new TransferHandler("icon"));
    MouseListener ml = new MouseAdapter(){
        public void mousePressed(MouseEvent e){
            JComponent jc = (JComponent)e.getSource();
            TransferHandler th = jc.getTransferHandler();
            th.exportAsDrag(jc, e, TransferHandler.COPY);
        }
    };
    dns.addMouseListener(ml);