Java Reference
In-Depth Information
between two points represented by its four arguments. The first two arguments are the x-
and y- coordinates for one endpoint, and the last two arguments are the coordinates for the
other endpoint. If you resize the window, the lines will scale accordingly, because the argu-
ments are based on the width and height of the panel. Resizing the window in this appli-
cation causes the system to call paintComponent to redraw the DrawPanel 's contents.
Class DrawPanelTest
To display the DrawPanel on the screen, you must place it in a window. You create a win-
dow with an object of class JFrame . In DrawPanelTest.java (Fig. 4.19), line 3 imports
class JFrame from package javax.swing . Line 10 in main creates a DrawPanel object,
which contains our drawing, and line 13 creates a new JFrame that can hold and display
our panel. Line 16 calls JFrame method setDefaultCloseOperation with the argument
JFrame.EXIT_ON_CLOSE to indicate that the application should terminate when the user
closes the window. Line 18 uses class JFrame 's add method to attach the DrawPanel to the
JFrame . Line 19 sets the size of the JFrame . Method setSize takes two parameters that
represent the width and height of the JFrame , respectively. Finally, line 20 displays the
JFrame by calling its setVisible method with the argument true . When the JFrame is
displayed, the DrawPanel 's paintComponent method (lines 9-22 of Fig. 4.18) is implicitly
called, and the two lines are drawn (see the sample outputs in Fig. 4.19). Try resizing the
window to see that the lines always draw based on the window's current width and height.
GUI and Graphics Case Study Exercises
4.1
Using loops and control statements to draw lines can lead to many interesting designs.
a)
Create the design in the left screen capture of Fig. 4.20. This design draws lines from
the top-left corner, fanning them out until they cover the upper-left half of the panel.
One approach is to divide the width and height into an equal number of steps (we found
15 steps worked well). The first endpoint of a line will always be in the top-left corner
(0, 0). The second endpoint can be found by starting at the bottom-left corner and
moving up one vertical step and right one horizontal step. Draw a line between the two
endpoints. Continue moving up and to the right one step to find each successive end-
point. The figure should scale accordingly as you resize the window.
Fig. 4.20 | Lines fanning from a corner.
 
Search WWH ::




Custom Search