package examples; import java.awt.event.*; import java.awt.*; import javax.swing.*; /* * @author Kenneth J. Goldman, Washington University, kjg@wustl.edu * Created: Feb 2, 2005 */ public class Dragger extends MouseAdapter implements MouseMotionListener { PanelWithOverlay panel; Container oldParent; // the old parent of component being dragged Point offset = new Point(); // the offset of the cursor from the upper left corner of the component being dragged public Dragger(PanelWithOverlay panel) { this.panel = panel; } public void control(Component x) { x.addMouseListener(this); x.addMouseMotionListener(this); } public void mouseDragged(MouseEvent me) { Component c = me.getComponent(); if (c.getParent() != panel) { // not yet in the overlay? oldParent = c.getParent(); offset = me.getPoint(); panel.raiseToOverlay(c); } Point p = c.getLocation(); c.setLocation(p.x + me.getX() - offset.x, p.y + me.getY() - offset.y); c.repaint(); } public void mouseReleased(MouseEvent me) { Component c = me.getComponent(); Point cursor = new Point(c.getX() + me.getX(), c.getY() + me.getY()); if (!panel.dropToContainerBeneath(c, cursor)) { oldParent.add(c); panel.revalidate(); panel.repaint(); } } public void mouseMoved(MouseEvent arg0) {} /* * Test program. */ public static void main(String args[]) { JPanel mainPanel = new JPanel(new GridLayout(1,0)); JPanel left = new JPanel(); left.setBackground(Color.GREEN); mainPanel.add(left); JButton one = new JButton("one"); one.setOpaque(false); left.add(one); JPanel right = new JPanel(); right.setBackground(Color.ORANGE); mainPanel.add(right); JButton two = new JButton("two"); two.setOpaque(false); right.add(two); PanelWithOverlay layeredPanel = new PanelWithOverlay(mainPanel); Dragger dragger = new Dragger(layeredPanel); dragger.control(one); dragger.control(two); JFrame f = new JFrame("Dragger test"); //f.setContentPane(layeredPanel); f.setLayout(new BorderLayout()); f.add(layeredPanel); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }