Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
Java How to Program, 6/e

ISBN:
0-13-148398-6
© 2005
pages: 1576
Buy the Book!
Amazon logo
InformIT logo

The following Java tutorial introduces the Java 2D API and demonstrates some of its powerful graphics capabilities, including shapes, strokes, fills, gradients, line styles, line joins, line end caps and general paths (which can be used to create your own two-dimensional shapes). This tutorial is intended for students and professionals who are already familiar with Java and Swing graphical user interface fundamentals. Download the examples for this tutorial here.

[Notes: This tutorial is an excerpt (Section 12.8) of Chapter 12, Graphics and Java 2D, from our best-selling textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. When you purchase this book you also get free access to the Web-based Java Multimedia Cyber Classroom, 6/e, for six months. The Cyber Classroom includes audio descriptions of the examples in Chapters 1-14, solutions to approximately one-half of the end-of-chapter exercises, interactive true/false self-assessment questions and a searchable Web-based e-book. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp. 697-706. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

Introduction to the Java 2D API (Continued)

 
Fig. 12.30 Creating JFrame to display shapes.
   1  // Fig. 12.30: Shapes.java
2
// Demonstrating some Java 2D shapes.
3
import javax.swing.JFrame;
4

5
public class Shapes
6
{
7
// execute application
8
public static void main( String args[] )
9
{
10
// create frame for ShapesJPanel
11
JFrame frame = new JFrame( "Drawing 2D shapes" );
12
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13

14
// create ShapesJPanel
15
ShapesJPanel shapesJPanel = new ShapesJPanel();
16

17
frame.add( shapesJPanel ); // add shapesJPanel to frame
18
frame.setSize( 425, 200 ); // set frame size
19
frame.setVisible( true ); // display frame
20
} // end main
21
} // end class Shapes

    Line 25 of Fig. 12.29 casts the Graphics reference received by paintComponent to a Graphics2D reference and assigns it to g2d to allow access to the Java 2D features.

    The first shape we draw is an oval filled with gradually changing colors. Lines 28–29 invoke Graphics2D method setPaint to set the Paint object that determines the color for the shape to display. A Paint object is an object that implements interface java.awt.Paint. The Paint object can be something as simple as one of the predeclared Color objects introduced in Section 12.3 (class Color implements Paint), or it can be an instance of the Java 2D API’s GradientPaint, SystemColor or TexturePaint classes. In this case, we use a GradientPaint object.

Page 1 | 2 | 3 | 4 | 5 | 6

Tutorial Index