import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; public class RectanglePanel extends JLabel implements MouseListener { private List toDraw; private Point lastClicked; public RectanglePanel() { super(); this.addMouseListener(this); toDraw = new LinkedList(); } public void paintComponent(Graphics g) { super.paintComponent(g); for(Rectangle r : this.toDraw) { g.drawRect(r.x, r.y, r.width, r.height); } } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } private static Rectangle createRectangle(Point from, Point to) { int x1 = (int)Math.min(from.getX(), to.getX()); int y1 = (int)Math.min(from.getY(), to.getY()); int x2 = (int)Math.max(from.getX(), to.getX()); int y2 = (int)Math.max(from.getY(), to.getY()); return new Rectangle(x1, y1, x2 - x1, y2 - y1); } public void mouseClicked(MouseEvent me) { if(lastClicked==null) lastClicked = me.getPoint(); else { toDraw.add(createRectangle(lastClicked, me.getPoint())); lastClicked = null; this.invalidate(); this.repaint(); this.revalidate(); } } public void mouseExited(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(new BorderLayout()); p.add(new RectanglePanel(), BorderLayout.CENTER); f.setContentPane(p); f.pack(); f.setVisible(true); } }