/** Based on textbook section 12.1 */ 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 = 300; private static final int PANEL_WIDTH = 300; // constructor - create a panel at some default location public RectanglePanel() { // inner class is mouse listener class DetectInput implements MouseListener { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); box.setLocation(x, y); repaint(); } public void mouseReleased(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); DetectInput listener = new DetectInput(); addMouseListener (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); } }