Download Object-Oriented Programming - HWS Department of Mathematics
Transcript
• fillRect(int x, int y, int width, int height) Draws a filled-in rectangle. This fills in the interior of the rectangle that would be drawn by drawRect(x,y,width,height). The extra pixel along the bottom and right edges is not included. The width and height parameters give the exact width and height of the rectangle. For example, if you wanted to fill in the entire component, you could say “g.fillRect(0, 0, getWidth(), getHeight());” • fillOval(int x, int y, int width, int height) Draws a filled-in oval. • fillRoundRect(int x, int y, int width, int height, int xdiam, int ydiam) Draws a filled-in rounded rectangle. • fill3DRect(int x, int y, int width, int height, boolean raised) Draws a filled-in three-dimensional rectangle. • fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draw a filled-in arc. This looks like a wedge of pie, whose crust is the arc that would be drawn by the drawArc method. 6.4.5 An Example Let’s use some of the material covered in this section to write a subclass of JPanel for use as a drawing surface. The panel can then be used in either an applet or a frame. All the drawing will be done in the paintComponent() method of the panel class. The panel will draw multiple copies of a message on a black background. Each copy of the message is in a random color. Five different fonts are used, with different sizes and styles. The message can be specified in the constructor; if the default constructor is used, the message is the string “Java!”. The panel works OK no matter what its size. Here’s an applet that uses the panel as its content pane: The source for the panel class is shown below. I use an instance variable called message to hold the message that the panel will display. There are five instance variables of type Font that represent different sizes and styles of text. These variables are initialized in the constructor and are used in the paintComponent() method. The paintComponent() method for the panel simply draws 25 copies of the message. For each copy, it chooses one of the five fonts at random, and it calls g.setFont() to select that font for drawing the text. It creates a random HSB color and uses g.setColor() to select that color for drawing. It then chooses random (x,y) coordinates for the location of the message. The x coordinate gives the horizontal position of the left end of the string. The formula used for the x coordinate, “−50 + (int)(Math.random() ∗ (width+40))” gives a random integer in the range from −50 to width−10. This makes it possible for the string to extend beyond the left edge or the right edge of the panel. Similarly, the formula for y allows the string to extend beyond the top and bottom of the applet. Here is the complete source code for the RandomStringsPanel import import import import java.awt.Color; java.awt.Font; java.awt.Graphics; javax.swing.JPanel; 126