猿问

Java-如何拖放JPanel及其组件

我有一个关于拖放的问题:我可以拖放标签,文本或图标。但是我想拖放一个JPanel及其所有组件(标签,文本框等)。

我怎样才能做到这一点 ?


冉冉说
浏览 641回答 3
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; }   @Overridepublic void addNotify() {    super.addNotify();    if (dgr == null) {        dragGestureHandler = new DragGestureHandler(this.actionPanel);        dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(                this,                DnDConstants.ACTION_MOVE,                dragGestureHandler);    }}@Overridepublic 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");

开满天机

在该DragGestureHandler::dragGestureRecognized方法中,变量被调用parent,因此隐藏了实例的parent变量。解决起来很容易。当我使用给定的代码时,我得到一个java.awt.dnd.InvalidDnDOperationException: Cannot find top-level for the drag source component。如果我将第一行(直到parent.repaint();方法的最底部,则不再抛出异常。区别在于new PanelTransferable(getPanel());从面板中 获取了。为什么会这样呢?)
随时随地看视频慕课网APP

相关分类

Java
我要回答