为了账号安全,请及时绑定邮箱和手机立即绑定

Java-如何拖放JPanel及其组件

Java-如何拖放JPanel及其组件

冉冉说 2019-12-03 14:49:32
我有一个关于拖放的问题:我可以拖放标签,文本或图标。但是我想拖放一个JPanel及其所有组件(标签,文本框等)。我怎样才能做到这一点 ?
查看完整描述

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");


查看完整回答
反对 回复 2019-12-03
?
开满天机

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());从面板中 获取了。为什么会这样呢?)

查看完整回答
反对 回复 2019-12-03
  • 3 回答
  • 0 关注
  • 640 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信