19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

0<br />

1<br />

2<br />

3<br />

4<br />

5<br />

6<br />

7<br />

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14<br />

g2d.draw(rectangle);<br />

g2d.translate(-6, 4);<br />

g2d.draw(rectangle);<br />

Figure 49.7<br />

(a) After applying g2d.translate(-6, 4), the subsequent rendering of<br />

the rectangle is moved by the specified distance relative <strong>to</strong> the<br />

previous position.<br />

Listing 49.2 gives a program that demonstrates the effect of<br />

translation of coordinates. Figure 49.8 shows a sample run of the<br />

program.<br />

Listing 49.2 TranslationDemo.java<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

import java.awt.*;<br />

import java.awt.geom.*;<br />

import javax.swing.*;<br />

public class TranslateDemo extends JApplet {<br />

public TranslateDemo() {<br />

add(new ShapePanel());<br />

}<br />

class ShapePanel extends JPanel {<br />

protected void paintComponent(Graphics g) {<br />

super.paintComponent(g);<br />

}<br />

}<br />

Graphics2D g2d = (Graphics2D)g;<br />

Rectangle2D rectangle = new Rectangle2D.Double(10, 10, 50, 60);<br />

java.util.Random random = new java.util.Random();<br />

for (int i = 0; i < 10; i++) {<br />

g2d.setColor(new Color(random.nextInt(256),<br />

random.nextInt(256), random.nextInt(256)));<br />

g2d.draw(rectangle);<br />

g2d.translate(20, 5);<br />

}<br />

9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!