1. Trang chủ
  2. » Công Nghệ Thông Tin

Java All-in-One Desk Reference For Dummies phần 10 docx

89 288 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 89
Dung lượng 1,48 MB

Nội dung

Creating Shapes 774 Shape round2 = new RoundRectangle2D.Float(210, 10, 60, 80, 50, 75); Here, the arc’s width is 50, and its height is 75. Creating ellipses An ellipse is a round shape that fits within a rectangular area. Thus, the con- structor for the Ellipse2D.Float class is similar to the Rectangle2D. Float constructor. Here’s an example that creates an ellipse where the bounding rectangle is a square: Shape ellipse1 = new Ellipse2D.Float(10, 110, 80, 80); Note that if the bounding rectangle happens to be a square, the ellipse is a circle. This one is the first shape in the second row in Figure 2-2. Here’s the code for the second ellipse in the figure: Shape ellipse2 = new Ellipse2D.Float(110, 110, 80, 40); Here, the ellipse fits inside a rectangle whose width is 80 and height is 40. Thus, the ellipse is short and wide, kind of like me. If I ate a little less and exercised a little more, maybe I’d look more like the third ellipse, created with this code: Shape ellipse3 = new Ellipse2D.Float(210, 110, 40, 80); Creating arcs Another useful type of shape is an arc, which is a segment of an ellipse. To create an arc, you supply the bounding rectangle that contains the ellipse. Here are the parameters you need to specify: ✦ The starting angle for the arc in degrees — 0 is due east, or 3 o’clock as they say in the movies. ✦ The extent, which is an angle that represents how much of the ellipse the arc spans. This too is specified in degrees. The important thing to know is that the arc travels counterclockwise from the starting point. So if you specify 0 as the starting point and 90 as the extent, the arc travels from 3 o’clock to 12 o’clock high. ✦ One of three arc types: Arc2D.OPEN indicates that you want to draw just the arc itself. Arc2D.CHORD means you want to draw the arc, and then connect the ends with a straight line to create a closed shape. Arc2D.PIE means you want to connect the ends with straight lines back to the center of the ellipse to create a shape that looks like a piece of pie. 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 774 Book IX Chapter 2 Drawing Shapes Creating Shapes 775 Here’s an example that creates the first arc shown in the figure: Shape arc1 = new Arc2D.Float(10, 210, 80, 80, 90, 90, Arc2D.OPEN); The second arc is created with this statement: Shape arc1 = new Arc2D.Float(110, 210, 80, 80, 0, 180, Arc2D.CHORD); And the third arc (the pie slice) is created by this statement: Shape arc1 = new Arc2D.Float(210, 210, 45, 180, 45, 90, Arc2D.PIE); Looking at the ShapeMaker program Now that you’ve seen how to create a variety of shapes, you’re ready to take a glance at Listing 2-2, which draw the shapes that were shown earlier in Figure 2-2. This program relies on a very useful technique for any program that works with more than a few shapes. Instead of creating and drawing each shape separately in the paint method, the shapes are stored in an ArrayList object of type Shape. The shapes are created in the PaintComponent constructor, so the code that creates the shapes is exe- cuted only once. Then, in the paint method, an enhanced for loop is used to draw each shape in the ArrayList. This technique is especially handy for programs that let the user draw shapes. Each time the user draws a new shape, you just add the shape to the ArrayList. Then, whenever the paint method is called, all the shapes are drawn. LISTING 2-2 THE SHAPEMAKER PROGRAM import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.awt.geom.*; import java.util.*; public class ShapeMaker extends JFrame { public static void main(String [] args) { new ShapeMaker(); } public ShapeMaker() { this.setSize(300, 300); this.setTitle(“Shape Maker”); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(new PaintSurface(), BorderLayout.CENTER); continued 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 775 Creating Shapes 776 LISTING 2-2 (CONTINUED) this.setVisible(true); } private class PaintSurface extends JComponent { ArrayList<Shape> shapes = new ArrayList<Shape>(); Point startDrag, endDrag; Shape found = null; public PaintSurface() { Shape s; // a rectangle s = new Rectangle2D.Float(10, 10, 60, 80); shapes.add(s); // a rounded rectangle s = new RoundRectangle2D.Float(110, 10, 80, 80,10, 10); shapes.add(s); // a rounded rectangle s = new RoundRectangle2D.Float(210, 10, 60, 80, 50, 75); shapes.add(s); // a circle s = new Ellipse2D.Float(10, 110, 80, 80); shapes.add(s); // an ellipse s = new Ellipse2D.Float(110, 110, 80, 40); shapes.add(s); // another ellipse s = new Ellipse2D.Float(210, 110, 40, 80); shapes.add(s); // an arc s = new Arc2D.Float(10, 210, 80, 80, 90, 90, Arc2D.OPEN); shapes.add(s); // another arc s = new Arc2D.Float(110, 210, 80, 80, 0, 180, Arc2D.CHORD); shapes.add(s); // another arc s = new Arc2D.Float(210, 210, 80, 80, 45, 90, Arc2D.PIE); shapes.add(s); } public void paint(Graphics g) { 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 776 Book IX Chapter 2 Drawing Shapes Filling Shapes 777 Graphics2D g2 = (Graphics2D)g; // turn on antialiasing g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // draw background grid g2.setPaint(Color.LIGHT_GRAY); for (int i = 0; i < getSize().width; i += 10) g2.draw(new Line2D.Float(i, 0, i, getSize().height)); for (int i = 0; i < getSize().height; i += 10) g2.draw(new Line2D.Float(0, i, getSize().width, i)); // draw all the shapes in the array list g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2)); for (Shape s : shapes) g2.draw(s); } } } Filling Shapes As explained earlier in the chapter, you can fill a shape with a solid color by first calling the setPaint method to set the fill color, and then calling the fill method to fill the shape. For example: g2.setColor(Color.RED); g2.fill(rect1); Here, the fill color is set to red, and then the shape named rect1 is filled. But there’s more to filling than solid colors. In the following sections, you find out how to create fills that are partially transparent and fills that gradu- ally fade from one color to another. Drawing transparently Java 2D lets you create transparent shapes by specifying a compositing rule. The compositing rule can do more than just set the transparency, but its other uses are more advanced than this short chapter allows. So rather than go into all the gory details, just accept my word that to set the transparency, you must use this odd incantation: g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.50F)); 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 777 Filling Shapes 778 The key here is the float parameter value, which must be from 0.0 to 1.0. In this case, the transparency is set to 0.50F, which means that the shapes are 50% transparent. As a result, whatever is under the shape when it is drawn partially shows through. Using a gradient fill Instead of using a solid color, you can specify a gradient fill, which blends two colors by using the GradientPaint class, whose constructors are shown in Table 2-2. A gradient fill is created from two color points. Imagine a line drawn between these two points. The gradient fill varies the color smoothly from the color that’s set at the first point to the color set at the second point. Then, it extends the colors on this line at 90 degree angles to the line to fill an entire area. Table 2-2 Constructors of the GradientPaint Class Constructor Description GradientPaint(float x1, Creates a gradient in which the color at point x1, floaty1, Color c1, float y1 is color1, the color at point x2, y2 is x2, float y2, Color c2) color2, and points in between are smoothly blended. All points beyond the x1, y1 point have color1, and all points beyond the x2, y2 point have color2. GradientPaint(Point2D p1, Creates a gradient in which the color at point p1 Color c1, Point2D p2 is color1, the color at point p2 is color2, Color c2) and points in between are smoothly blended. All points beyond p1 have color1, and all points beyond p2 have color2. GradientPaint(float x1, Same as the first constructor, but if the cyclic floaty1, Color c1, float parameter is true, the gradient pattern repeats x2, float y2, Color c2, infinitely beyond the two points. boolean cyclic) GradientPaint(Point2D p1, Same as the second constructor, but if the Color c1, Point2D p2 Color cyclic parameter is true, the gradient pattern c2, boolean cyclic) repeats infinitely beyond the two points. Here’s an example that sets a gradient fill that varies the color from magenta to yellow: GradientPaint gp = new GradientPaint(0, 0, Color.MAGENTA, 0, 100, Color.YELLOW); 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 778 Book IX Chapter 2 Drawing Shapes Filling Shapes 779 Here are some suggestions for choosing the location of the two color points: ✦ The points are relative to the top-left corner of the component, not to the shape you’re filling. You usually want both points to lie at or near the edges of the shape you’re drawing. ✦ The easiest way to keep the number straight is to create variables named x, y, width, and height, and use these variables to create both the shapes and the gradient fills. ✦ If you want to have the first color at the top and the second color at the bottom, use (x, y) for the first point and (x, y+height) as the second point. ✦ If you want to have the first color at the left and the second color at the right, use (x, y) for the first point and (x+width, y) as the second point. ✦ Each point is painted with the full color you specify. If you want a band of solid color on the edges of the object before the gradient begins, choose points that are somewhat inside the object. For example, use (10, 10) and (width-10, height-10). ✦ If you use the third or fourth constructors and specify true for the cyclic parameter, the gradient pattern repeats itself. Then, you want to pick points that are closer together so you can see the repetition within your object. For example, if the width of the object is 150, pick points such as (0, 0) and (0, 50) to see the cycle repeat three times within the object. Table 2-3 shows four different examples of gradient fills created with the GradientPaint class. Each of the rectangles is 100 x 100. The table also shows the location of the points for each fill relative to x, y, width, and height. For each fill, the color for point 1 is black, and for point 2, white. Table 2-3 Four Gradient Fill Examples Gradient Fill Name Point 1 (Black) Point 2 (White) gp1 x, y x, y + height gp2 x, y x + width, y gp3 x, y+35 x, y + height + 35 gp4 x+35, y+35 x+width-35, y+height-35 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 779 Rotating and Translating 780 Here’s the code that creates these four gradient fills: GradientPaint gp1 = new GradientPaint(x, y, Color.BLACK, x, y + h, Color.WHITE); GradientPaint gp2 = new GradientPaint(x, y, Color.BLACK, x + w, y, Color.WHITE); GradientPaint gp3 = new GradientPaint(x, y+35, Color.BLACK, x, y+h-35, Color.WHITE, true); GradientPaint gp4 = new GradientPaint(x+35, y+35, Color.BLACK, x+w-35, y+h-35, Color.WHITE, true); Using this code as a starting point, you can devise many different variations to create your own fills. Rotating and Translating This section describes two methods of the Graphics2D class that modify how a shape is drawn: ✦ The translate method moves the (0, 0) point from the top-left corner to any arbitrary point. ✦ The rotate method rotates the component’s coordinate system so that shapes are drawn at an angle. Translate method The translate method takes two parameters, namely the x and y coordinate of the point you want to designate as the center of the universe. For many graphics applications, translating to the center of the component is useful, so (0, 0) is in the middle of the component. Then, points with a negative x value appear to the left of center, and points with a negative y value appear above center. Here’s a code snippet that does that regardless of the size of the component: int cx = getSize().width / 2; // center X; int cy = getSize().height / 2; // center Y; g2.translate(cx, cy); Rotate method Rotation is a little more complicated. The rotate method itself is simple enough — it takes just a single parameter that rotates the coordinate system by the angle you specify. For example: g2.rotate(angle); 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 780 Book IX Chapter 2 Drawing Shapes Rotating and Translating 781 The angle isn’t measured in degrees. Instead, it’s measured in radians, which if you’ll remember back to your high-school math is the length of the arc subtended by the angle (assuming the radius is 1). Java’s Math class has a handy toRadians method that automatically converts degrees to radians. So, to rotate the coordinate space by 45 degrees, you use this statement: g2.rotate(Math.toRadians(45)); Note that the rotate method rotates the entire coordinate space for the component you’re painting on, not just a single shape. As a result, to draw a shape rotated around its center, you first translate to the center of the shape you want to rotate, call the rotate method, and then draw the shape. The Graphics2D class provides a convenient version of the rotate method that does that for you automatically. It takes three parameters: the rotation angle and the x and y coordinates of the point around which you want to rotate. For example: g2.rotate(Math.toRadians(45), 100, 150); Here, the coordinate space is rotated 45 degrees around point 100, 150. (The translation is only temporary; the rotate method restores the previous translation after it does the rotation.) Here’s an example from a paint method that creates an ellipse, and then draws it several times at different rotations: int x = 50; int y = 75; int width = 200; int height = 100; Shape r1 = new Ellipse2D.Float(x, y, width, height); for (int angle = 0; angle <= 360; angle += 45) { g2.rotate(Math.toRadians(angle), x + width/2, y + height/2); g2.setPaint(Color.YELLOW); g2.fill(r1); g2.setStroke(new BasicStroke(4)); g2.setPaint(Color.BLACK); g2.draw(r1); } Here, the rotate method is called inside a for loop that varies the angle from 0 degrees through 360 degrees in 45 degree increments. Assuming the paint method has set antialiasing and 50% transparency and has drawn the line grids shown in the previous examples, Figure 2-3 shows how the shapes drawn by these statements appear. 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 781 Drawing Text 782 Drawing Text You can use the drawString method to draw the text contained in a string. This method accepts three parameters: the string to be drawn and the x and y coordinates of the lower-left corner of the first character to be drawn (technically speaking, the start of the baseline for the text). For example: g2.drawString(“This is some text!”, 100, 50); Here, the string “This is some text!” is drawn at point (100, 50). The current stroke, color, translation, and rotation apply to the text that’s drawn, as well as the current font that you specify via the setFont method. This method accepts a Font object, like this: g2.setFont(new Font(“Times New Roman”, Font.PLAIN, 36)); Here, the font is set to 36-point Times New Roman. For more information about creating fonts, refer to Book IX, Chapter 1. Letting the User Draw on a Component In many applications, you need to let the user doodle directly on a panel. To do that, you need to create listeners that listen for mouse events such as clicks, drags, or just basic movement. Then, you need to coordinate those listeners with the paint method so that the mouse events generated by the user are translated into shapes that are drawn on the component. Table 2-4 lists the mouse events you need to listen for in programs that let the user draw shapes. Figure 2-3: Rotated shapes. 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 782 Book IX Chapter 2 Drawing Shapes Letting the User Draw on a Component 783 Table 2-4 Mouse Events and Listeners MouseListener Methods Description void mouseClicked(MouseEvent e) The user clicked a mouse button. void mouseEntered(MouseEvent e) The mouse entered a component. void mouseExited(MouseEvent e) The mouse exited a component. void mousePressed(MouseEvent e) The user pressed a mouse button. void mouseReleased(MouseEvent e) The user released a mouse button. MouseMotionListener Methods Description void mouseMoved(MouseEvent e) The user moved the mouse with- out pressing a button. void mouseDragged(MouseEvent e) The user moved the mouse while a button was pressed. MouseEvent Methods Description int getButton() Gets the mouse button that has been clicked, pressed, or released. The result can be BUTTON1, BUTTON2, BUTTON3, or NOBUTTON. int getClickCount() Gets the number of clicks to determine if the user has double- or triple-clicked. Point getPoint() Gets the mouse position as a Point object. int getX() Gets the x position. int getY() Gets the y position. Note that both the MouseListener and MouseMotionListener inter- faces have corresponding adapter classes named MouseAdapter and MouseMotionAdapter. If you use one or both of these adapter classes, you only have to override the methods for the events you want to respond to. (For more information about adapter classes and listeners, refer to Book VI, Chapter 2.) To see how mouse events can be used to create programs that let the user draw on-screen, take a look at a simple program that lets the user draw rec- tangles. The basic technique used by the program goes something like this: ✦ When the user presses the mouse button, you make a note of the loca- tion to use as the starting point of the rectangle to be drawn. 57_58961X bk09ch02.qxd 3/29/05 3:30 PM Page 783 [...]... Portable Network Graphics format, which was designed specifically for portability and network access You’d think this would be the most common format for Java applications, because Java too was designed for portability and network access But although Java does indeed support PNG, GIF and JPEG are the more popular choices Java does not directly support other common graphics file formats such as BMP (Windows... contains a picture Java supports pictures in several different formats, including: ✦ GIF: Graphics Interchange Format, commonly used for small images such as those used for button icons and such ✦ JPEG: An organization called the Joint Photographic Experts Group (hence the name JPEG) devised this format to store photographic images in a compressed form JPEG is the preferred form for larger images ✦... do so: *((.jpg)|(.gif)|(.png)) For more information about file filters, refer to Book VIII, Chapter 1 And for more information about regular expressions, turn to Book V, Chapter 3 Playing Sounds and Making Music Java provides built-in support for playing sound and music files You can play sound and music files in a variety of formats, including wave files in several formats (WAV, AU, RMF, and AIFF... waiting for the entire image to load Icons are typically small images used to provide visual cues for what a button does However, the ImageIcon class isn’t just for small images You can use it to display large images as well, as long as you’re willing to hold up your program while the image loads For Swing applications, that’s not usually a problem For applets, you may want to consider alternatives for. .. chooser includes a filter so only JPEG, GIF, and PNG files are listed For more information about the JFileChooser class, refer to Book VIII, Chapter 1 Figure 3-2: The Picture Frame application in action Using the Image Class 797 Book IX Chapter 3 LISTING 3-1: THE PICTURE FRAME APPLICATION javax.swing.*; java. awt.event.*; java. awt.*; java. io.*; public class PictureFrame extends JFrame implements ActionListener... drawn several rectangles Listing 2-3 provides the complete code for the program Letting the User Draw on a Component 785 Book IX Chapter 2 Drawing Shapes Figure 2-4: The Drawing Board program in action LISTING 2-3: THE DRAWINGBOARD PROGRAM import import import import import javax.swing.*; java. awt.event.*; java. awt.*; java. awt.geom.*; java. util.*; public class DrawingBoard extends JFrame { public static... features that are presented in several different chapters throughout this book Specifically, you find information about drawing shapes in Book IX, Chapter 2 For information about working with threads, refer to Book V, Chapter 1 For information creating event listeners, see Book VI, Chapter 2 And for details about creating and running applets, see Book VII, Chapter 1 Animating a Sprite In animation... a MouseListener installed Then, each time the mouseClicked method is called, the sound is played LISTING 3-2: THE MOUSECLICKER PROGRAM import import import import import javax.swing.*; java. awt.event.*; java. awt.*; java. applet.*; java. net.URL; public class MouseClicker extends JFrame { AudioClip click; public static void main(String [] args) { new MouseClicker(); } public MouseClicker() { this.setSize(400,... bitmap), or WMF (Windows Media Format) The easiest way to deal with this limitation is to simply convert your images to GIF, JPEG, or PNG Programs that can do that conversion are readily available If you insist on using images in those formats, you can get third-party packages that do it Hop on the Internet and cruise to your favorite search service and look for Java and the format you want to support... RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // draw background grid g2.setPaint(Color.LIGHT_GRAY); for (int i = 0; i < getSize().width; i += 10) { Shape line = new Line2D.Float( i, 0, i, getSize().height); g2.draw(line); } for (int i = 0; i < getSize().height; i += 10) { Shape line = new Line2D.Float( 0, i, getSize().width, i); g2.draw(line); } // draw the shapes Color[] colors = . Rectangle2D.Float (10, 10, 60, 80); shapes.add(s); // a rounded rectangle s = new RoundRectangle2D.Float( 110, 10, 80, 80 ,10, 10) ; shapes.add(s); // a rounded rectangle s = new RoundRectangle2D.Float( 210, 10, . common format for Java applications, because Java too was designed for portability and network access. But although Java does indeed support PNG, GIF and JPEG are the more popular choices. Java. Arc2D.Float (10, 210, 80, 80, 90, 90, Arc2D.OPEN); shapes.add(s); // another arc s = new Arc2D.Float( 110, 210, 80, 80, 0, 180, Arc2D.CHORD); shapes.add(s); // another arc s = new Arc2D.Float( 210, 210,

Ngày đăng: 12/08/2014, 19:21

TỪ KHÓA LIÊN QUAN