AWT Notice 2

Note that when using Swing components, you should override the method paintComponent, but when using AWT components, you should override their paint method instead. The AWT alternative to JPanel is simply Panel. When adding an AWT component, you must add it directly to the top-level container. Swing components must be added to the content pane of the top-level container. Note that the content pane of a Swing top-level container, such as JFrame or JApplet, is a JPanel itself. Also, if you are adding only one component, such as our JPanel derivative DisplayArea, instead of adding this to the content pane, you can use setContentPane(myDisplayArea), cutting out the middleman as it were. This is a Swing feature.


It is important to understand about components and containers because this technique is used a lot in Java and can be very advantageous in many respects. For example, you may split your screen area up into different components and then add mouse listeners to the individual areas of the screen, making handling mouse events easy, relative to that area of the screen. However, if you are making a serious game, we recommend that you stick to one drawing area (i.e., the paint method of the frame or applet) and perform your drawing all at once. If you use multiple components to represent sections of your screen, they cannot overlap, and drawing routines are completely separate, as each of the components will have its own paint method for drawing to its given rectangular screen area. This would be a problem, say, if you had a component representing the main game display and another component for an inventory of weapons.

What if you wanted to have your graphics overlap from the main game screen to another component, such as an inventory? Perhaps some sparks will fly off or something or maybe an inventory item will be dragged onto the main game screen from the inventory. There are a whole host of reasons you would want to do this; however, this would be virtually impossible with separate drawing methods for each component or at least a nightmare to code. For the drawing example apps that follow, we will add a component for displaying our graphics for convenience but will stick to the top-level paint methods for the passive rendering examples in the "Rendering" section later in the chapter.