Java Reference
In-Depth Information
7
// Create a MovableMessagePanel instance for moving a message
MovableMessagePanel p = new MovableMessagePanel
8
9
10
11 // Place the message panel in the frame
12 add(p);
13 }
14
15 /** Main method */
16 public static void main(String[] args) {
17 MoveMessageDemo frame = new MoveMessageDemo();
18 frame.setTitle( "MoveMessageDemo" );
19 frame.setSize( 200 , 100 );
20 frame.setLocationRelativeTo( null ); // Center the frame
21 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22 frame.setVisible( true );
23 }
24
25
create a panel
( "Welcome to Java" );
// Inner class: MovableMessagePanel draws a message
static class MovableMessagePanel extends JPanel {
26
27
inner class
private String message = "Welcome to Java" ;
28
private int x = 20 ;
29
private int y = 20 ;
30
31 /** Construct a panel to draw string s */
32 public MovableMessagePanel(String s) {
33 message = s;
34
35 @Override /** Handle mouse-dragged event */
36
37 // Get the new location and repaint the screen
38 x = e.getX();
39 y = e.getY();
40 repaint();
41 }
42
43 @Override /** Handle mouse-moved event */
44
45 }
46 );
47 }
48
49 @Override
50 protected void paintComponent(Graphics g) {
51 super .paintComponent(g);
52 g.drawString(message, x, y);
53 }
54 }
55 }
set a new message
anonymous listener
addMouseMotionListener( new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
override handler
new location
repaint
public void mouseMoved(MouseEvent e) {
}
paint message
The MovableMessagePanel class extends JPanel to draw a message (line 26). Addition-
ally, it handles redisplaying the message when the mouse is dragged. This class is defined as
an inner class inside the main class because it is used only in this class. Furthermore, the
inner class is defined as static because it does not reference any instance members of the
main class.
The MouseMotionListener interface contains two handlers, mouseMoved and
mouseDragged , for handling mouse-motion events. When you move the mouse with a button
pressed, the mouseDragged method is invoked to repaint the viewing area and display the
 
Search WWH ::




Custom Search