Changes for an Application

On the companion CD in the source directory for this chapter, we have also included the previous code in an application with one change that you need to be aware of. Apart from the obvious differences between applications and applets that we have looked at in previous chapters, there is the issue of the position of mouse events in a windowed application. When a mouse or mouse motion listener is added to the main JFrame object, the position of the mouse is registered in reference to the very top corner of the window, where the top leftmost pixel of its border appears and not at the top leftmost position of the displayable area. One way to handle this in our application would be to translate the mouse event's x and y position back by the left and top border insets before adding the event to the event processor, as follows:

public void mousePressed(MouseEvent e) {     e.translatePoint(-DISPLAY_X, -DISPLAY_Y);     eventProcessor.addEvent(e); } 

This is going by our coding standard so far in this book of saving the border insets (left and top) to the variables DISPLAY_X and DISPLAY_Y, respectively, for a real-time rendering application.

We could also, however, simply add the mouse listeners to the content pane of the main JFrame instead of the JFrame itself.

// In JFrame constructor getContentPane().addMouseListener(this);

This code is added to the extra example on the companion CD and gives us mouse events with coordinates relative to the displayable area within the window's borders.

Note 

When we close an application, we do this using the WindowEvent passed to the windowClosing method of a window listener. When this method is invoked, it is also not synchronized with the main loop thread, as it comes from the Event Dispatch Thread. However, in our examples, this doesn't really matter, as all we do is set the thread variable loop to null, which in turn causes the main game loop and program to terminate. You could quite easily add the WindowEvent to the event processor and handle it there if closing the window included some extra code that needed to be synchronized with the main loop. We can do this, as a WindowEvent is also derived from AWTEvent, like the other events such as MouseEvent and KeyEvent. You can also test the event's ID for handling against the static variable WindowEvent.WINDOW_CLOSING.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net