I have a panel with lists and buttons. The lists set MouseAdapter with mouseClick(). I added to the panel MouseAdapter with mousePressed() and mouseReleased() and MouseMotionAdapter with mouseDragged.
Drag and drop only works if you click on the panel.
How to make the drag work even if I clicked on the list?
Simple examlpe:
public class DragTest extends JFrame{
private boolean drag;
private Point btnCoord;
private Point startPoint;
public DragTest(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500,500);
setLayout(null);
final JPanel panel = new JPanel();
final JButton button = new JButton();
button.setText("Button");
button.setSize(30,60);
button.setLocation(50, 50);
panel.setLayout(null);
setContentPane(panel);
panel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (drag){
panel.setLocation(btnCoord.x-(startPoint.x-e.getX()),btnCoord.y-(startPoint.y-e.getY()));
}
}
});
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
drag = true;
startPoint = e.getPoint();
btnCoord = panel.getLocation();
}
@Override
public void mouseReleased(MouseEvent e) {
drag = false;
}
});
getContentPane().add(button);
}
public static void main(String[] args) {
JFrame frame = new DragTest();
frame.setVisible(true);
}
}
If you drag panel, all work fine, if start drag button, then button intercept event.
The above code has many errors…
null/AbsoluteLayoutManager. Have a look at Laying Out Components Within a Container.setSizeon components andJFrame(if correct Layout Manager is implemented you can simply add components and callpack()onJFrame.revalidate()andrepaint()on container after adding/removing components from a visible container.I have been working on my own little
ComponentDragAPI which will allow us to drag Swing components across aJComponentor over multipleJComponents. It is by no means error free though (especially the multiple components part just finished it today so you never know)You would create
JButtonand add toJPanel:Than create an instance of
ComponentDragclass by passing argument of you container i.eJFrame/JDialogorJWindowand register the draggable components and callsetName("Droppable")on yourJPanelto allow dragging and dropping to take place correctly especially across multiple JComponents etc, you would only do this for theJPanels etc that you want the ability to drop Swing components too:and your good to go :).
Here are 2 full examples for analysis purposes:
1) Show the logic to move
JButtons and re-position the accordingly usingComponentDragand overriding itscomponentDroppedmethod:Before drag:
After 4 dragged to 1 position:
2) Simply shows how to drag 2
JLabels acrossJPanelsBefore Drag me label dragged:
After label dragged: