-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path13.20.java.java
62 lines (47 loc) · 1.54 KB
/
13.20.java.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Fig. 13.20: MouseDetails.java
// Demonstrating mouse clicks and distinguishing between mouse buttons. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
private int xPos, yPos;
// set title bar String; register mouse listener; size and show window
public Main()
{
super( "Mouse clicks and buttons" );
addMouseListener( new MouseClickHandler() );
setSize( 350, 150 );
setVisible( true );
}
// draw String at location where mouse was clicked
public void paint( Graphics g )
{
// call superclass paint method
super.paint( g );
g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]",
xPos, yPos );
}
public static void main( String args[] )
{
Main application = new Main();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
// inner class to handle mouse events
private class MouseClickHandler extends MouseAdapter {
// handle mouse click event and determine which button was pressed
public void mouseClicked( MouseEvent event )
{
xPos = event.getX();
yPos = event.getY();
String title = "Clicked " + event.getClickCount() + " time(s)";
if ( event.isMetaDown() ) // right mouse button
title += " with right mouse button";
else if ( event.isAltDown() ) // middle mouse button
title += " with center mouse button";
else // left mouse button
title += " with left mouse button";
setTitle( title ); // set title bar of window
repaint();
} // end method mouseClicked
} // end private inner class MouseClickHandler
} // end class MouseDetails