(Optional) GUI and Graphics Case Study: Creating Simple Drawings

(Optional) GUI and Graphics Case Study Creating Simple Drawings

One of Java's appealing features is its graphics support that enables programmers to visually enhance their applications. This section introduces one of Java's graphical capabilitiesdrawing lines. It also covers the basics of creating a window to display a drawing on the computer screen.

To begin drawing in Java, you must first understand Java's coordinate system (Fig. 4.18), a scheme for identifying every point on the screen. By default, the upper-left corner of a GUI component has the coordinates (0, 0). A coordinate pair is composed of an x-coordinate (the horizontal coordinate) and a y-coordinate (the vertical coordinate). The x-coordinate is the horizontal location moving from left to right. The y-coordinate is the vertical location moving top to bottom. The x-axis describes every horizontal coordinate, and the y-axis every vertical coordinate.

Figure 4.18. Java coordinate system. Units are measured in pixels.

Coordinates are used to indicate where graphics should be displayed on a screen. Coordinate units are measured in pixels. A pixel is a display monitor's smallest unit of resolution. (The term pixel stands for "picture element.")

Our first drawing application simply draws two lines from the corners. Class DrawPanel (Fig. 4.19) performs the actual drawing, while class DrawPanelTest (Fig. 4.20) creates a window to display the drawing. In class DrawPanel, the import statements in lines 34 allow us to use class Graphics (from package java.awt), which provides various methods for drawing text and shapes onto the screen, and class JPanel (from package javax.swing), which provides an area on which we can draw.

Figure 4.19. Using drawLine to connect the corners of a panel.

(This item is displayed on pages 158 - 159 in the print version)

 1 // Fig. 4.19: DrawPanel.java
 2 // Draws two crossing lines on a panel.
 3 import java.awt.Graphics; 
 4 import javax.swing.JPanel;
 6 public class DrawPanel extends JPanel
 7 {
 8 // draws an X from the corners of the panel
 9 public void paintComponent( Graphics g )
10 {
11 // call paintComponent to ensure the panel displays correctly
12 super.paintComponent( g );
14 int width = getWidth(); // total width 
15 int height = getHeight(); // total height
17 // draw a line from the upper-left to the lower-right
18 g.drawLine( 0, 0, width, height );
20 // draw a line from the lower-left to the upper-right
21 g.drawLine( 0, height, width, 0 );
22 } // end method paintComponent
23 } // end class DrawPanel

Figure 4.20. Creating JFrame to display DrawPanel.

(This item is displayed on page 160 in the print version)

 1 // Fig. 4.20: DrawPanelTest.java
 2 // Application to display a DrawPanel.
 3 import javax.swing.JFrame;
 5 public class DrawPanelTest
 6 {
 7 public static void main( String args[] )
 8 {
 9 // create a panel that contains our drawing
10 DrawPanel panel = new DrawPanel();
12 // create a new frame to hold the panel
13 JFrame application = new JFrame();
15 // set the frame to exit when it is closed
16 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
18 application.add( panel ); // add the panel to the frame 
19 application.setSize( 250, 250 ); // set the size of the frame
20 application.setVisible( true ); // make the frame visible 
21 } // end main
22 } // end class DrawPanelTest

Line 6 uses the keyword extends to indicate that class DrawPanel is an enhanced type of JPanel. The keyword extends represents a so-called inheritance relationship in which our new class DrawPanel begins with the existing members (data and methods) from class JPanel. The class from which DrawPanel inherits, JPanel, appears to the right of keyword extends. In this inheritance relationship, JPanel is called the superclass and DrawPanel is called the subclass. This results in a DrawPanel class that has the attributes (data) and behaviors (methods) of class JPanel as well as the new features we are adding in our DrawPanel class declaration (specifically, the ability to draw two lines along the diagonals of the panel). Inheritance will be explained in more detail in Chapter 9.

Every JPanel, including our DrawPanel, has a paintComponent method (lines 922), which the system automatically calls every time it needs to display the JPanel. Method paintComponent must be declared as shown on line 9otherwise, the system will not call the method. This method is called when a JPanel is first displayed on the screen, when it is covered then uncovered by a window on the screen and when the window in which it appears is resized. Method paintComponent requires one argument, a Graphics object, that is provided for you by the system when it calls paintComponent.

The first statement in every paintComponent method you create should always be

 super.paintComponent( g );

This will ensure that the panel is properly rendered on the screen before we begin drawing on it. Next, lines 14 and 15 call two methods that class DrawPanel inherits from class JPanel. Because DrawPanel extends JPanel, DrawPanel can use any public methods that are declared in JPanel. Methods getWidth and getHeight return the width and the height of the JPanel respectively. Lines 1415 store these values in the local variables width and height. Finally, lines 18 and 21 use the Graphics reference g to call method drawLine to draw the two lines. Method drawLine draws a line between two points represented by its four arguments. The first two arguments are the x- and y- coordinates for one endpoint of the line, and the last two arguments are the coordinates for the other endpoint of the line. If you resize the window, the lines will scale accordingly because the arguments are based on the width and height of the panel. Note that resizing the window in this application causes the system to call paintComponent to redraw the DrawPanel's contents.

To display the DrawPanel on the screen, we must place it in a window. You create a window with an object of class JFrame. In DrawPanelTest.java (Fig. 4.20), line 3 imports class JFrame from package javax.swing. Line 10 in the main method of class DrawPanelTest creates an instance of class DrawPanel, which contains our drawing, and line 13 creates a new JFrame that can hold and display our panel. Line 16 calls method setDefaultCloseOperation with the argument JFrame.EXIT_ON_CLOSE to indicate that the application should terminate when the user closes the window. Line 18 uses JFrame's add method to attach the DrawPanel containing our drawing to the JFrame. Line 19 sets the size of the JFrame. Method setSize takes two parametersthe first parameter is the width of the JFrame, and the second is the height. Finally, line 20 displays the JFrame. When the JFrame is displayed, the DrawPanel's paintComponent method (lines 922 of Fig. 4.19) is called, and the two lines are drawn (see the sample outputs in Fig. 4.20). Try resizing the window to see that the lines always draw based on the window's current width and height.

For the next several GUI and graphics sections, there will be very few changes required in the main method. As we introduce additional drawing capabilities, most of the changes will come in the class that extends JPanel, since that is where the drawing takes place.

GUI and Graphics Case Study Exercises


Using loops and control statements to draw lines can lead to many interesting designs.

  1. Create the design in the left screen capture of Fig. 4.21. This design draws lines from the top-left corner, fanning out the lines until they cover the upper-left half of the panel. One approach is to divide the width and height into an equal number of steps (we found 15 steps worked well). The first endpoint of a line will always be in the top-left corner (0, 0). The second endpoint can be found by starting at the bottom-left corner and moving up one vertical step and moving right one horizontal step. Draw a line between the two endpoints. Continue moving up and to the right one step to find each successive endpoint. The figure should scale accordingly as you resize the window.

    Figure 4.21. Lines fanning from a corner.

  2. Modify your answer in part (a) to have lines fan out from all four corners, as shown in the right screen capture of Fig. 4.21. Lines from opposite corners should intersect along the middle.

Figure 4.22 displays two additional designs created using while loops and drawLine.

Figure 4.22. Line art with loops and drawLine.

  1. Create the design in the left screen capture of Fig. 4.22. Begin by dividing each edge into an equal number of increments (we chose 15 again). The first line starts in the topleft corner and ends one step right on the bottom edge. For each successive line, move down one increment on the left edge and right one increment on the bottom edge. Continue drawing lines until you reach the bottom-right corner. The figure should scale as you resize the window so that the endpoints always touch the edges.
  2. Modify your answer in part (a) to mirror the design in all four corners, as shown in the right screen capture of Fig. 4.22.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look


Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams


Searching and Sorting

Data Structures



Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2



Accessing Databases with JDBC


JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Similar book on Amazon

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net