3 回答

TA貢獻(xiàn)1798條經(jīng)驗 獲得超3個贊
該代碼是對MadProgrammer的巨大幫助。對于任何想要使用這些類,但想要從要拖動的面板中的按鈕發(fā)起拖動的人,我只需將擴(kuò)展的JPanel替換為一個JButton,即可在構(gòu)造函數(shù)中使用面板:
public class DragActionButton extends JButton {
private DragGestureRecognizer dgr;
private DragGestureHandler dragGestureHandler;
private JPanel actionPanel;
DragActionButton (JPanel actionPanel, String buttonText)
{
this.setText(buttonText);
this.actionPanel = actionPanel;
}
@Override
public void addNotify() {
super.addNotify();
if (dgr == null) {
dragGestureHandler = new DragGestureHandler(this.actionPanel);
dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
this,
DnDConstants.ACTION_MOVE,
dragGestureHandler);
}
}
@Override
public void removeNotify() {
if (dgr != null) {
dgr.removeDragGestureListener(dragGestureHandler);
dragGestureHandler = null;
}
dgr = null;
super.removeNotify();
}
}
那么您可以在創(chuàng)建按鈕時執(zhí)行此操作:
this.JButtonDragIt = new DragActionButton(this.JPanel_To_Drag, "button-text-here");

TA貢獻(xiàn)1786條經(jīng)驗 獲得超13個贊
在該DragGestureHandler::dragGestureRecognized
方法中,變量被調(diào)用parent
,因此隱藏了實例的parent
變量。解決起來很容易。當(dāng)我使用給定的代碼時,我得到一個java.awt.dnd.InvalidDnDOperationException: Cannot find top-level for the drag source component
。如果我將第一行(直到parent.repaint();
方法的最底部,則不再拋出異常。區(qū)別在于new PanelTransferable(getPanel());
從面板中 獲取了。為什么會這樣呢?)
添加回答
舉報