Java Reference
In-Depth Information
System. exit(0) ;
if (charList.size() > MAX SIZE) {
System. out . println ( "You lose!" );
System. exit(0) ;
} );
t. start() ;
frame . setSize (200 , 200) ;
frame. setVisible( true );
Note that we have also added code to determine when the player wins or loses. Every
time interval the counter is incremented by one. If the user is able to survive till the counter
reaches 150, then they win. Alternatively, if the ArrayList becomes more than 10 charac-
ters, then the player loses. After running the program, we may find that it is dicult to win
if the timer is set at 200 milliseconds. Accordingly, we can adjust the game by changing the
three constants at the beginning of the code. This is a good design because one can change
the parameters of the game just by changing the values of the constants.
10.3.2 Mouse Listeners
We will next create a simple drawing program. In the previous chapter, we showed how
different shapes can be displayed inside a panel. Here, we will describe how the user can
draw any arbitrary collection of freehand shapes. When the user presses the left mouse
button, the program will start drawing the shape. It will keep drawing the shape until the
user releases the mouse button. In order to implement the program, we need to be aware
of two types of Java interfaces that can be used to capture mouse events: MouseListener
and MouseMotionListener . Information about the two interfaces is shown below.
interface MouseListener
void mouseClicked(MouseEvent e) ;
void mouseEntered(MouseEvent e) ;
void mouseExited(MouseEvent e ) ;
void mousePressed (MouseEvent e ) ;
void mouseReleased(MouseEvent e) ;
interface MouseMotionListener {
mouseDragged(MouseEvent e) ;
mouseMoved(MouseEvent e ) ;
Note that while a MouseListener is notified when the buttons of the mouse are clicked,
a MouseMotionListener is notified when the mouse is moved. In our drawing game, we
will use both listeners. Of course, we will inherit from the abstract classes MouseAdapter
and MouseMotionAdapter in order to avoid the need to override all methods. These classes
contain empty implantations of all the methods of the interfaces. One can register a mouse
listener with a panel by writing the following code.
MouseAdapter mouseAdapter = . . .
panel . addMouseListener (mouseAdapter) ;
Looking at the code for the key listeners and the mouse listeners, a pattern has emerged.
Search WWH ::

Custom Search