3 回答

TA贡献1798条经验 获得超3个赞
该代码是对MadProgrammer的巨大帮助。对于任何想要使用这些类,但想要从要拖动的面板中的按钮发起拖动的人,我只需将扩展的JPanel替换为一个JButton,即可在构造函数中使用面板:
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();
}
}
那么您可以在创建按钮时执行此操作:
this.JButtonDragIt = new DragActionButton(this.JPanel_To_Drag, "button-text-here");

TA贡献1786条经验 获得超13个赞
在该DragGestureHandler::dragGestureRecognized
方法中,变量被调用parent
,因此隐藏了实例的parent
变量。解决起来很容易。当我使用给定的代码时,我得到一个java.awt.dnd.InvalidDnDOperationException: Cannot find top-level for the drag source component
。如果我将第一行(直到parent.repaint();
方法的最底部,则不再抛出异常。区别在于new PanelTransferable(getPanel());
从面板中 获取了。为什么会这样呢?)
添加回答
举报