Java - Как перетащить JPanel с его компонентами
У меня есть вопрос о перетаскивании: я могу сбросить метки, текст или значок. Но я хочу перетащить JPanel со всеми его компонентами (Label, Textbox и т. Д.).
Как я могу это сделать?
2 ответа
Это решение работает. Некоторые пещеры для начала.
Я не использовал API TransferHandler. Мне это не нравится, это слишком ограничительно, но это личное (то, что он делает, это хорошо), так что это может не соответствовать вашим ожиданиям.
Я тестировал с BorderLayout. Если вы хотите использовать другие макеты, вам придется попытаться понять это. Подсистема DnD предоставляет информацию о точке мыши (при перемещении и опускании).
Итак, что нам нужно:
DataFlavor. Я решил сделать это, потому что это допускает большее ограничение
public class PanelDataFlavor extends DataFlavor {
// This saves me having to make lots of copies of the same thing
public static final PanelDataFlavor SHARED_INSTANCE = new PanelDataFlavor();
public PanelDataFlavor() {
super(JPanel.class, null);
}
}
Передаваемый. Какая-то обертка, которая упаковывает данные (наш JPanel) с кучей DataFlavors (в нашем случае, просто PanelDataFlavor)
public class PanelTransferable implements Transferable {
private DataFlavor[] flavors = new DataFlavor[]{PanelDataFlavor.SHARED_INSTANCE};
private JPanel panel;
public PanelTransferable(JPanel panel) {
this.panel = panel;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
// Okay, for this example, this is overkill, but makes it easier
// to add new flavor support by subclassing
boolean supported = false;
for (DataFlavor mine : getTransferDataFlavors()) {
if (mine.equals(flavor)) {
supported = true;
break;
}
}
return supported;
}
public JPanel getPanel() {
return panel;
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
Object data = null;
if (isDataFlavorSupported(flavor)) {
data = getPanel();
} else {
throw new UnsupportedFlavorException(flavor);
}
return data;
}
}
"DragGestureListener"
Для этого я создал простой DragGestureHandler, который принимает "JPanel" в качестве содержимого для перетаскивания. Это позволяет обработчику жестов стать самоуправляемым.
public class DragGestureHandler implements DragGestureListener, DragSourceListener {
private Container parent;
private JPanel child;
public DragGestureHandler(JPanel child) {
this.child = child;
}
public JPanel getPanel() {
return child;
}
public void setParent(Container parent) {
this.parent = parent;
}
public Container getParent() {
return parent;
}
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
// When the drag begins, we need to grab a reference to the
// parent container so we can return it if the drop
// is rejected
Container parent = getPanel().getParent();
setParent(parent);
// Remove the panel from the parent. If we don't do this, it
// can cause serialization issues. We could overcome this
// by allowing the drop target to remove the component, but that's
// an argument for another day
parent.remove(getPanel());
// Update the display
parent.invalidate();
parent.repaint();
// Create our transferable wrapper
Transferable transferable = new PanelTransferable(getPanel());
// Start the "drag" process...
DragSource ds = dge.getDragSource();
ds.startDrag(dge, Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR), transferable, this);
}
@Override
public void dragEnter(DragSourceDragEvent dsde) {
}
@Override
public void dragOver(DragSourceDragEvent dsde) {
}
@Override
public void dropActionChanged(DragSourceDragEvent dsde) {
}
@Override
public void dragExit(DragSourceEvent dse) {
}
@Override
public void dragDropEnd(DragSourceDropEvent dsde) {
// If the drop was not successful, we need to
// return the component back to it's previous
// parent
if (!dsde.getDropSuccess()) {
getParent().add(getPanel());
getParent().invalidate();
getParent().repaint();
}
}
}
Итак, это основы. Теперь нам нужно соединить все это вместе...
Итак, в панель, которую я хочу перетащить, я добавил:
private DragGestureRecognizer dgr;
private DragGestureHandler dragGestureHandler;
@Override
public void addNotify() {
super.addNotify();
if (dgr == null) {
dragGestureHandler = new DragGestureHandler(this);
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();
}
Причиной использования уведомления добавления / удаления таким образом является поддержание чистоты системы. Это помогает предотвратить доставку событий в наш компонент, когда они нам больше не нужны. Также предусмотрена автоматическая регистрация. Вы можете использовать свой собственный метод setDraggable.
Это сторона сопротивления, теперь для стороны падения.
Во-первых, нам нужен DropTargetListener:
public class DropHandler implements DropTargetListener {
@Override
public void dragEnter(DropTargetDragEvent dtde) {
// Determine if we can actually process the contents coming in.
// You could try and inspect the transferable as well, but
// there is an issue on the MacOS under some circumstances
// where it does not actually bundle the data until you accept the
// drop.
if (dtde.isDataFlavorSupported(PanelDataFlavor.SHARED_INSTANCE)) {
dtde.acceptDrag(DnDConstants.ACTION_MOVE);
} else {
dtde.rejectDrag();
}
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
@Override
public void dragExit(DropTargetEvent dte) {
}
@Override
public void drop(DropTargetDropEvent dtde) {
boolean success = false;
// Basically, we want to unwrap the present...
if (dtde.isDataFlavorSupported(PanelDataFlavor.SHARED_INSTANCE)) {
Transferable transferable = dtde.getTransferable();
try {
Object data = transferable.getTransferData(PanelDataFlavor.SHARED_INSTANCE);
if (data instanceof JPanel) {
JPanel panel = (JPanel) data;
DropTargetContext dtc = dtde.getDropTargetContext();
Component component = dtc.getComponent();
if (component instanceof JComponent) {
Container parent = panel.getParent();
if (parent != null) {
parent.remove(panel);
}
((JComponent)component).add(panel);
success = true;
dtde.acceptDrop(DnDConstants.ACTION_MOVE);
invalidate();
repaint();
} else {
success = false;
dtde.rejectDrop();
}
} else {
success = false;
dtde.rejectDrop();
}
} catch (Exception exp) {
success = false;
dtde.rejectDrop();
exp.printStackTrace();
}
} else {
success = false;
dtde.rejectDrop();
}
dtde.dropComplete(success);
}
}
Наконец, нам нужно зарегистрировать цель отбрасывания с заинтересованными сторонами... В те контейнеры, которые могут поддерживать отбрасывание, вы хотите добавить
DropTarget dropTarget;
DropHandler dropHandler;
.
.
.
dropHandler = new DropHandler();
dropTarget = new DropTarget(pnlOne, DnDConstants.ACTION_MOVE, dropHandler, true);
Лично я инициализирую в addNotify и располагаю в removeNotify
dropTarget.removeDropTargetListener(dropHandler);
Просто быстрое замечание о addNotify, я уже несколько раз подряд вызывал его, так что вы можете еще раз проверить, что вы еще не установили цели удаления.
Вот и все.
Вы также можете найти некоторые из следующих интересов
http://rabbit-hole.blogspot.com.au/2006/05/my-drag-image-is-better-than-yours.html
http://rabbit-hole.blogspot.com.au/2006/08/drop-target-navigation-or-you-drag.html
http://rabbit-hole.blogspot.com.au/2006/04/smooth-jlist-drop-target-animation.html
Было бы напрасно не проверять их, даже если просто из интереса.
2018 Обновление
Итак, спустя 4 года после написания оригинального кода, похоже, произошли некоторые изменения в том, как работает API, по крайней мере, в MacOS, что вызывает ряд проблем.
Первый DragGestureHandler
вызывал NullPointerException
когда DragSource#startDrag
был вызван. Похоже, это связано с настройкой контейнера parent
ссылка на null
(удалив его из родительского контейнера).
Так что вместо этого я изменил dragGestureRecognized
метод для удаления panel
от родителя ПОСЛЕ DragSource#startDrag
назывался...
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
// When the drag begins, we need to grab a reference to the
// parent container so we can return it if the drop
// is rejected
Container parent = getPanel().getParent();
System.out.println("parent = " + parent.hashCode());
setParent(parent);
// Remove the panel from the parent. If we don't do this, it
// can cause serialization issues. We could overcome this
// by allowing the drop target to remove the component, but that's
// an argument for another day
// This is causing a NullPointerException on MacOS 10.13.3/Java 8
// parent.remove(getPanel());
// // Update the display
// parent.invalidate();
// parent.repaint();
// Create our transferable wrapper
System.out.println("Drag " + getPanel().hashCode());
Transferable transferable = new PanelTransferable(getPanel());
// Start the "drag" process...
DragSource ds = dge.getDragSource();
ds.startDrag(dge, null, transferable, this);
parent.remove(getPanel());
// Update the display
parent.invalidate();
parent.repaint();
}
Я также изменил DragGestureHandler#dragDropEnd
метод
@Override
public void dragDropEnd(DragSourceDropEvent dsde) {
// If the drop was not successful, we need to
// return the component back to it's previous
// parent
if (!dsde.getDropSuccess()) {
getParent().add(getPanel());
} else {
getPanel().remove(getPanel());
}
getParent().invalidate();
getParent().repaint();
}
А также DropHandler#drop
@Override
public void drop(DropTargetDropEvent dtde) {
boolean success = false;
// Basically, we want to unwrap the present...
if (dtde.isDataFlavorSupported(PanelDataFlavor.SHARED_INSTANCE)) {
Transferable transferable = dtde.getTransferable();
try {
Object data = transferable.getTransferData(PanelDataFlavor.SHARED_INSTANCE);
if (data instanceof JPanel) {
JPanel panel = (JPanel) data;
DropTargetContext dtc = dtde.getDropTargetContext();
Component component = dtc.getComponent();
if (component instanceof JComponent) {
Container parent = panel.getParent();
if (parent != null) {
parent.remove(panel);
parent.revalidate();
parent.repaint();
}
((JComponent) component).add(panel);
success = true;
dtde.acceptDrop(DnDConstants.ACTION_MOVE);
((JComponent) component).invalidate();
((JComponent) component).repaint();
} else {
success = false;
dtde.rejectDrop();
}
} else {
success = false;
dtde.rejectDrop();
}
} catch (Exception exp) {
success = false;
dtde.rejectDrop();
exp.printStackTrace();
}
} else {
success = false;
dtde.rejectDrop();
}
dtde.dropComplete(success);
}
Важно отметить, что указанные выше модификации, вероятно, не требуются, но они существовали после того, как я заставил операции работать снова...
Еще одна проблема, с которой я столкнулся, была куча NotSerializableException
s
Я был обязан обновить DragGestureHandler
а также DropHandler
классы...
public class DragGestureHandler implements DragGestureListener, DragSourceListener, Serializable {
//...
}
public public class DropHandler implements DropTargetListener, Serializable {
//...
}
Работоспособный пример...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test implements Serializable {
public static void main(String[] args) {
new Test();;
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(1, 2));
JPanel container = new OutterPane();
DragPane drag = new DragPane();
container.add(drag);
add(container);
add(new DropPane());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class OutterPane extends JPanel {
public OutterPane() {
setBackground(Color.GREEN);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
}
}
DragPane
import java.awt.Color;
import java.awt.Dimension;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import javax.swing.JPanel;
public class DragPane extends JPanel {
private DragGestureRecognizer dgr;
private DragGestureHandler dragGestureHandler;
public DragPane() {
System.out.println("DragPane = " + this.hashCode());
setBackground(Color.RED);
dragGestureHandler = new DragGestureHandler(this);
dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, dragGestureHandler);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
DropPane
import java.awt.Color;
import java.awt.Dimension;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import javax.swing.JPanel;
public class DropPane extends JPanel {
DropTarget dropTarget;
DropHandler dropHandler;
public DropPane() {
setBackground(Color.BLUE);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
@Override
public void addNotify() {
super.addNotify(); //To change body of generated methods, choose Tools | Templates.
dropHandler = new DropHandler();
dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, dropHandler, true);
}
@Override
public void removeNotify() {
super.removeNotify(); //To change body of generated methods, choose Tools | Templates.
dropTarget.removeDropTargetListener(dropHandler);
}
}
DragGestureHandler
, DropHandler
, PanelDataFlavor
а также PanelTransferable
классы остаются прежними, за исключением изменений, о которых я упоминал выше. Все эти классы автономны, внешние классы, в противном случае это вызывает дополнительные NotSerializableException
проблемы
Заметки
Возможно, что имея DragGestureHandler
управляемый одним и тем же компонентом, который перетаскивается, может быть причиной всех проблем, но у меня нет времени для расследования
Следует отметить, что я не предлагаю и не одобряю манипулирование компонентами таким образом, так как это легко может оказаться в ситуациях, когда решение может работать сегодня, но не будет работать завтра. Я предпочитаю передавать состояние или данные вместо этого - гораздо более стабильный.
Я пробовал дюжину других примеров, основанных на той же концепции, представленной в исходном ответе, которая просто передавала состояние, и все они работали без проблем, это было только при попытке передать Component
s не удалось - пока не было применено вышеуказанное исправление
Этот код ОГРОМНАЯ помощь 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");