1. 2. 3. 4. 5.
6.
/* Mouse Event Handling in a Frame Window Example This java example shows how to handle mouse events in a Frame window using MouseListener. */ java.awt.Frame; java.awt.Graphics; java.awt.event.MouseEvent; java.awt.event.MouseListener; java.awt.event.WindowAdapter; java.awt.event.WindowEvent;
7. import 8. import 9. import 10. import 11. import 12. import
13.
14. /* 15. * To create 16. * Frame and 17. */
18.
a stand alone window, class should be extended from not from Applet class.
19. public
20.
class HandleMouseListenerInWindowExample extends Frame implements MouseListener{ int x=0, y=0; String strEvent = ""; HandleMouseListenerInWindowExample(String title){ //call superclass constructor with window title super(title); //add window listener addWindowListener(new MyWindowAdapter(this)); //add mouse listener addMouseListener(this); //set window size setSize(300,300); //show the window setVisible(true); }
21. 22.
23.
24.
25.
26. 27.
28.
29. 30.
31.
32. 33.
34.
35. 36.
37.
38. 39. 40.
41. 42. 43.
44.
45.
public void mouseClicked(MouseEvent e) { strEvent = "MouseClicked"; x = e.getX(); y = getY();
46. 47. 48.
49. 50.
51. 52.
repaint(); }
53. 54. 55. 56. 57.
58.
public void mousePressed(MouseEvent e) { strEvent = "MousePressed"; x = e.getX(); y = getY(); repaint(); }
59.
60. 61.
62. 63. 64. 65. 66.
67.
public void mouseReleased(MouseEvent e) { strEvent = "MouseReleased"; x = e.getX(); y = getY(); repaint(); }
68.
69. 70.
71. 72. 73. 74. 75.
76.
public void mouseEntered(MouseEvent e) { strEvent = "MouseEntered"; x = e.getX(); y = getY(); repaint(); }
77.
78. 79.
80. 81. 82. 83. 84.
85.
public void mouseExited(MouseEvent e) { strEvent = "MouseExited"; x = e.getX(); y = getY(); repaint(); }
86.
87. 88.
89. 90. 91.
92.
public void paint(Graphics g){ g.drawString(strEvent + " at " + x + "," + y, 50,50); } public static void main(String[] args) { HandleMouseListenerInWindowExample myWindow = new HandleMouseListenerInWindowExample("Window With Mouse Events Example"); }
93.
94.
95. 96. 97.
98.
99.
100.
101.
} class MyWindowAdapter extends WindowAdapter{ HandleMouseListenerInWindowExample myWindow = null; MyWindowAdapter(HandleMouseListenerInWindowExample this.myWindow = myWindow; } public void windowClosing(WindowEvent we){ myWindow.setVisible(false); } }
102.
103.
104.
105.
106.
myWindow){
107. 108.
109.
110. 111. 112. 113.
xample Output