26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Chapter 11 Graphics and <strong>Java</strong>2D 607<br />

Common <strong>Program</strong>ming Error 11.1<br />

Spelling any static Color class constant with an initial capital letter is a syntax error. 11.1<br />

Two Color construc<strong>to</strong>rs are shown in Fig. 11.4—one that takes three int arguments,<br />

and one that takes three float arguments, with each argument specifying the amount of<br />

red, green and blue, respectively. The int values must be between 0 and 255 and the float<br />

values must be between 0.0 and 1.0. The new Color object will have the specified<br />

amounts of red, green and blue. Color methods getRed, getGreen and getBlue<br />

return integer values from 0 <strong>to</strong> 255 representing the amount of red, green and blue, respectively.<br />

Graphics method getColor returns a Color object representing the current<br />

drawing color. Graphics method setColor sets the current drawing color.<br />

The application of Fig. 11.5 demonstrates several methods from Fig. 11.4 by drawing<br />

filled rectangles and strings in several different colors.<br />

1 // Fig. 11.5: ShowColors.java<br />

2 // Demonstrating Colors.<br />

3<br />

4 // <strong>Java</strong> core packages<br />

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

6 import java.awt.event.*;<br />

7<br />

8 // <strong>Java</strong> extension packages<br />

9 import javax.swing.*;<br />

10<br />

11 public class ShowColors extends JFrame {<br />

12<br />

13 // construc<strong>to</strong>r sets window's title bar string and dimensions<br />

14 public ShowColors()<br />

15 {<br />

16 super( "Using colors" );<br />

17<br />

18 setSize( 400, 130 );<br />

19 setVisible( true );<br />

20 }<br />

21<br />

22 // draw rectangles and Strings in different colors<br />

23 public void paint( Graphics g )<br />

24 {<br />

25 // call superclass's paint method<br />

26 super.paint( g );<br />

27<br />

28 // set new drawing color using integers<br />

29 g.setColor( new Color( 255, 0, 0 ) );<br />

30 g.fillRect( 25, 25, 100, 20 );<br />

31 g.drawString( "Current RGB: " + g.getColor(), 130, 40 );<br />

32<br />

33 // set new drawing color using floats<br />

34 g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );<br />

35 g.fillRect( 25, 50, 100, 20 );<br />

36 g.drawString( "Current RGB: " + g.getColor(), 130, 65 );<br />

Fig. Fig. 11.5 11.5 Demonstrating setting and getting a Color (part 1 of 2).<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

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

Saved successfully!

Ooh no, something went wrong!