I wrote a simple implementation of the Game of life with java applets.
Here’s is the source code for the Applet and the Model.
When I click the button to get the next iteration these Exceptions get thrown.
Z:\GameOfLife>appletviewer driver.html
Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException:
65
at GameOfLifeApplet.mouseClicked(GameOfLifeApplet.java:63)
at java.awt.Component.processMouseEvent(Component.java:6219)
at java.awt.Component.processEvent(Component.java:5981)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre ad.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre ad.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Try this code that adds the button once rather than every call to
paint(). Note that this source still throws AIOOBE if you click outside the grid (and not on the button), but that seems like a basic logic error you should investigate once the button is fixed.Further tips
nulllayouts. The custom rendered area does not need it, and the button should be sized and positioned using a layout manager (with maybe a border to pad it out).Update
This code implements the 2nd suggestion from above ‘use layouts’, but leaves it as an exercise for the reader to update the components to something that might be used in this millennium (i.e. Swing).
The source below ‘cheats’ in a sense to show the GUI at it’s natural size. This is tricky to do in an applet, since the size is set by the HTML. But put the GUI into a Swing based
JOptionPaneand it can be put on-screen, packed to its natural size, in just a couple of lines of code.Here is what it looks like at the ‘natural size’ (I played with some numbers, to make the GUI smaller).
Other matters
Panel. This gets around the common problems of painting directly to a top-level container. It also allows easy re-use of the same GUI in different containers. In this case both an applet, and for the ‘application’ (which would usually be put in a frame), aJOptionPane. It is now what is known as a ‘hybrid applet/application’ (easier for testing).Ecosystem(shrugs) informs the layout what size it prefers to be. This helps us to avoid needing to set the size or bounds of anything.