/** Based on example from another book. */ import java.awt.event.*; // for mouse listener import java.awt.*; // for graphics import javax.swing.*; // for JPanel public class RectanglePanel extends JPanel { private Rectangle box; private static final int BOX_X = 100; private static final int BOX_Y = 100; private static final int BOX_HEIGHT = 30; private static final int BOX_WIDTH = 20; private static final int PANEL_HEIGHT = 500; private static final int PANEL_WIDTH = 300; // constructor - create a panel at some default location public RectanglePanel() { // Our inner class is mouse listener // Instead of implementing the MouseListener interface, we can // equivalently extend MouseAdapter. // One fun thing we can try is to instead move the rectangle // when the mouse is *dragged* - this a a mouse motion event. // We would extend MouseMotionAdapter and implement the function // mouseDragged(MouseEvent e)... class DetectInput extends MouseAdapter //class DetectInput extends MouseMotionAdapter { public void mousePressed(MouseEvent e) //public void mouseMoved(MouseEvent e) { int x = e.getX(); int y = e.getY(); box.setLocation(x, y); repaint(); } } setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); DetectInput listener = new DetectInput(); addMouseListener (listener); //addMouseMotionListener(listener); } // The purpose of paintComponent() is to "paint" the geometric figures that // we have in our panel. It's analogous to paint() in an applet. // We need to call the generic JPanel paintComponent() first so that the // panel starts out clean. Comment it out and see what happens! public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.draw(box); } }