我试图熟悉java中的拖放,但我发现的所有教程都是......(让我生气)
我想要的只是从 JList 中拖动一个“PublicUserLabel”(包含在一个名为“UserPanel”的自制 JPanel 中)并将其放入从 JTabbedPanel 初始化的自制类中。拖动对象本身而不是它的字符串表示非常重要!!!
这就是我到目前为止所拥有的:PublicUserLabel
public class PublicUserLabel extends JLabel implements DragSourceListener, DragGestureListener, Transferable
{
private DragSource ds;
private PublicUser user;
public PublicUserLabel(PublicUser user)
{
super(user.getName());
this.user = user;
ds = new DragSource();
ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
@Override
public void dragGestureRecognized(DragGestureEvent e)
{
ds.startDrag(e, DragSource.DefaultCopyDrop, this, this);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
{
if (flavor.equals(PublicUserFlavor.publicUserFlavor))
{
return this;//TODO ?
}
throw new UnsupportedFlavorException(flavor);
}
@Override
public DataFlavor[] getTransferDataFlavors()
{
DataFlavor[] df = new DataFlavor[2];
df[0] = DataFlavor.stringFlavor;
df[1] = PublicUserFlavor.publicUserFlavor;
return df;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return flavor.equals(PublicUserFlavor.publicUserFlavor);
}
//some more methods
}
用户面板:
public class UserPanel extends JPanel
{
private JTextField search;
private List<PublicUser> allUser;
private JList<PublicUserLabel> list;
private JScrollPane scrollPane;
private DefaultListModel<PublicUserLabel> listModel;
public UserPanel()
{
allUser = new LinkedList<PublicUser>();
listModel = new DefaultListModel<PublicUserLabel>();
list = new JList<PublicUserLabel>(listModel);
list.setDragEnabled(true);
公共用户风格:
public class PublicUserFlavor extends DataFlavor
{
public static DataFlavor publicUserFlavor;
static
{
publicUserFlavor = new DataFlavor(PublicUser.class, "PublicUser");
}
}
选项卡面板:
public class TabPanel extends JTabbedPane implements DropTargetListener
{
public TabPanel()
{
setTabPlacement(JTabbedPane.BOTTOM);
addNewTabComponent("bla");
addNewTabComponent("blub");
setDropTarget(new DropTarget(this, this));
}
@Override
public void drop(DropTargetDropEvent e)
{
Transferable transferable = e.getTransferable();
if (transferable.isDataFlavorSupported(PublicUserFlavor.publicUserFlavor))
{
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try
{
Object o = transferable.getTransferData(PublicUserFlavor.publicUserFlavor);
System.out.println(o);
if (o instanceof PublicUserLabel)
{
PublicUserLabel l = (PublicUserLabel)o;
PublicUser u = l.getUser();
System.out.println(u);
}
}
catch (UnsupportedFlavorException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.getDropTargetContext().dropComplete(true);
}
}
在 drop 方法中有一些 syso,如果用户被拖放到面板中,则应执行这些 syso。但事实并非如此。我做错了什么吗?谢谢你的帮忙!