由于TransferHandler
属性仅传输JLabel
的'text'属性。我将如何处理图像文件?我需要定制一个TransferHandler
吗?
最佳答案
我将如何处理图像文件?
不知道您是要同时传输图标还是同时传输图标和文本。
如果只需要Icon,则可以使用默认的TransferHandler:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragIcon extends JPanel
{
public DragIcon()
{
TransferHandler iconHandler = new TransferHandler( "icon" );
MouseListener dragListener = new DragMouseAdapter();
JLabel label1 = new JLabel("Label1");
label1.setTransferHandler( iconHandler );
label1.addMouseListener(dragListener);
label1.setIcon( new ImageIcon("copy16.gif") );
JLabel label2 = new JLabel("Label2");
label2.setTransferHandler( iconHandler );
label2.addMouseListener(dragListener);
add( label1 );
add( label2 );
}
private class DragMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
// handler.exportAsDrag(c, e, TransferHandler.MOVE);
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Drag Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DragIcon());
frame.setLocationByPlatform( true );
frame.setSize(200, 100);
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}