MouseEventDemo.java

Download MouseEventDemo.java

 1: // Demonstrates mouseClicked and MouseMoved events, by
 2: // redrawing a box where you click, and having a star follow
 3: // the cursor.
 4: //
 5: // Written 2016 by Wayne Pollock, Tampa Florida USA
 6: 
 7: import javax.swing.*;
 8: import java.awt.*;
 9: import java.awt.event.*;
10: 
11: class MouseEventDemo extends JPanel
12: {
13:     // Holds box and star coordinates.
14:     // The star coordinates are actually (0,0), but then the star is
15:     // drawn under the cursor.  By faking the initial coords to the bottom-
16:     // right of the bounding box, the star is drawn above and to the left of
17:     // the cursor.
18:     int boxX = 0, boxY = 0, starX = 10, starY = 10;
19:     Polygon star = new Polygon();
20: 
21:     public MouseEventDemo()
22:     {
23:         // Construct a 5-point star in a 10x10 box:
24:         star.addPoint(5, 0);
25:         star.addPoint(7, 3);
26:         star.addPoint(10, 3);
27:         star.addPoint(8, 6);
28:         star.addPoint(8, 10);
29:         star.addPoint(5, 7);
30:         star.addPoint(2, 10);
31:         star.addPoint(2, 6);
32:         star.addPoint(0, 3);
33:         star.addPoint(3, 3);
34: 
35:         addMouseListener(new MouseAdapter()
36:         {
37:             @Override
38:             public void mousePressed(MouseEvent e)
39:             {
40:                 boxX = e.getX();
41:                 boxY = e.getY();
42:                 repaint();
43:             }
44:         });
45: 
46:         addMouseMotionListener(new MouseMotionAdapter()
47:         {
48:             @Override
49:             public void mouseMoved(MouseEvent e)
50:             {
51:                 int deltaX = e.getX() - starX;
52:                 starX = e.getX();
53:                 int deltaY = e.getY() - starY;
54:                 starY = e.getY();
55:                 star.translate( deltaX, deltaY );
56:                 repaint();
57:             }
58:         });
59:     }
60: 
61:     @Override
62:     public void paintComponent(Graphics g)
63:     {
64:         super.paintComponent(g);
65:         Graphics2D g2 = (Graphics2D) g;
66:         g2.fillRect(boxX, boxY, 10, 10);
67:         g2.fill( star );
68:     }
69: 
70:    public static void main ( String [] args )
71:    {
72:       JFrame frame = new JFrame( "MouseEventDemo - Click to draw rect" );
73:       frame.add( new MouseEventDemo() );
74:       frame.setSize( 400, 200 );
75:       frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
76:       frame.setVisible( true );
77:    }
78: }