Changes for an app

On the companion CD in the source directory for this chapter, we have also included the previous code in an app with one change that you need to be aware of. Apart from the obvious differences between apps and applets that we have looked at in previous chapters, there is the issue of the position of mouse events in a windowed app. 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 app 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);

This is going by our coding standard so far in this tutorial of saving the border insets (left and top) to the variables DISPLAY_X and DISPLAY_Y, respectively, for a real-time rendering app. 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.


When we close an app, 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.