import java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class MoveGraphics extends JPanel { int cursorX = 100; int cursorY = 100; int width = 20; int height = 20; boolean dragging = false; public MoveGraphics() { addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); Rectangle r = new Rectangle(cursorX, cursorY, width, height); //Must check for dragging in the if-statement //below because the cursor might get outside //the rectangle while dragging. if (r.contains( x, y ) || dragging) { //User starts dragging. dragging = true; cursorX = e.getX(); cursorY = e.getY(); repaint(); } } }); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { //User stops dragging. dragging = false; } }); } public void paintComponent(Graphics g) { //This is were drawing is done. Do not touch the paint //method. //Call super or the panels background will not //be redrawn. super.paintComponent(g); //Draw the rectangle where the user has placed it. g.drawRect(cursorX, cursorY, width, height); } public static void main(String[] args) { JFrame f = new JFrame("simple drag and drop"); f.getContentPane().add(new MoveGraphics(), BorderLayout.CENTER); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } } ); f.setSize(300, 300); f.setVisible(true); } }