Java Reference
In-Depth Information
9.6 Important Points
1. In order to create a window in Java, create a class that inherits from the
JFrame
class
and instantiate it.
2. Call the
setVisible
method on a window in order to make it visible.
3. Initialize the content of the window inside the constructor of the class that inherits
from the
JFrame
class.
4. The
paintComponent
method does the drawing inside a
JPanel
. It will be called mul-
tiple times (i.e., every time the window needs to be repainted). The
paintComponent
method takes as input an object of type
Graphics
, which is used to do the drawing.
Always call the super class at the beginning of the
paintComponent
method, which
guarantees that you will start painting on a blank canvas.
5. The
paintComponent
method only displays the data. It should never generate new
data.
6. Never call the
paintComponent
method directly. Instead, call the
repaint
method in
order to refresh a panel.
9.7 Exercises
1. Write code that displays the picture from Figure 9.4, that is, a circle and a horizontal
and vertical line segment through its center.
2. Write code that displays the window from Figure 9.5. The ball is displayed as an
image (search the Internet for a blue ball to get a similar image). Set the initial size
of the window appropriately and make the window non-resizable.
3. Write a program that displays
GAME OVER
in the middle of a window. The text color
should be white, while the background color should be red.
FIGURE 9.4:
Picture for Exercise 1.