Outline
20.1 Test-Driving the Screen Saver Application 20.2 Inheritance Overview
20.3 Graphics Overview
20.4 Creating the Screen Saver Application
20.5 Using Inheritance to create the
MyRectangleClass 20.6 Graphics in Java
20.7 Completing the Screen Saver Application 20.8 Wrap-Up
Tutorial 20 – Screen Saver Application
Introducing Inheritance and Graphics
Objectives
• In this tutorial, you will learn to:
– Understand inheritance.
– Form new classes quickly from existing classes using inheritance.
– Use the Graphics object to draw rectangles on a JPanel .
Application
Application Requirements
A local retail chain continuously displays a single screen on its customer
service monitors. To prevent this image from being burned into the monitor,
the owner of the chain has asked you to create an application that will
display rectangles of random size, position, and color every .25 seconds
when no customers need help. This program should also contain a Clear
JButton to clear the previously drawn rectangles
.Application (Cont.)
• Running the completed application
– Open a Command Prompt
• Change to
ScreenSaverdirectory
• Type
java ScreenSaverApplication (Cont.)
Figure 20.1 Running the completed Screen Saver application.
Application (Cont.)
Figure 20.2 Screen Saver application after running for a few seconds.
Application (Cont.)
Figure 20.3 Screen Saver application after clicking the Clear JButton.
20.2 Inheritance Overview
• New class inherits members from an existing class
– The pre-existing class is called the superclass
• Direct superclass
• Indirect superclass
– The new class is called the subclass
• Class hierarchy
– Defines the inheritance relationship
• “is-a” relationship
• “has-a” relationship
20.2 Inheritance Overview (Cont.)
Superclass Subclasses
Student GraduateStudent, UndergraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount
Figure 20.4 Inheritance examples.
20.2 Inheritance Overview (Cont.)
Figure 20.5 Inheritance hierarchy for university CommunityMembers.
20.2 Inheritance Overview (Cont.)
Figure 20.6 Inheritance hierarchy for Shapes.
20.2 Inheritance Overview (Cont.)
• extend keyword
• Overriding methods
– New method supercedes the inherited method
20.3 Graphics Overview
• Graphics terms
– Pixel – a display monitor’s smallest unit of resolution
– Coordinate pair – composed of an x-coordinate and a y-coordinate.
– x-coordinate – the horizontal distance moving right from the upper-left corner.
– y-coordinate – the vertical distance moving down from the upper-left corner.
– The x-axis describes every horizontal coordinate
– The y-axis describes every vertical coordinate.
20.3 Graphics Overview (Cont.)
Figure 20.7 Java coordinate system. Units are measured in pixels.
20.3 Graphics Overview (Cont.)
• The Graphics object
– Allows you to draw pixels on the screen to represent text and other graphical objects
• Lines
• Ellipses
• Rectangles
• Other polygons
20.4 Creating the Screen Saver Application
When the application is executed Start the timer
When the timer interval expires (every quarter second) Get random values for x, y, width and height Pick a random color
Create a rectangle
Place the rectangle in the ArrayList Repaint the DrawJPanel
When paintComponent is called
Create an Iterator for the ArrayList
Use the Iterator to reference each Rectangle in the ArrayList and draw each rectangle When the user clicks the Clear Jbutton
Clear the ArrayList
Repaint the DrawJPanel
(Cont.)
Action Component/Object Event/Method
Start the timer drawTimer start
Every quarter second drawTimer Timer interval expires Get random values for x, y,
width and height
randomNumber
Pick a random color randomNumber
Create a rectangle rectangle Place the rectangle in the
ArrayList
rectangleArrayList
Repaint the DrawJPanel drawingJPanel
Figure 20.8 Screen Saver application’s ACE table. (Part 1 of 2)
(Cont.)
Action Component/Object Event/Method
paintComponent is called drawingJPanel paintComponent
is called Create an Iterator for the
ArrayList
rectangleArrayList
Reference each Rectangle in the ArrayList
rectangleIterator
Draw each rectangle currentRectangle
User clicks the Clear JButton
clearJButton User clicks the
Clear JButton
Clear the ArrayList rectangleArrayList
Repaint the DrawJPanel drawingJPanel
Figure 20.8 Screen Saver application’s ACE table. (Part 2 of 2)
MyRectangle Class
Figure 20.9 Declaring class MyRectangle.
MyRectangle
inherits from
Rectangle
• extends keyword indicates that MyRectangle inherits from
Rectangle .
MyRectangle Class (Cont.)
Figure 20.10 Instance variable to hold the fill color.
Creating an instance variable for color
MyRectangle Class (Cont.)
Declaring class
MyRectangle’s constructor
Figure 20.11 Calling the superclass’s constructor.
• superclass constructor call syntax
•
MyRectangle Class (Cont.)
Figure 20.12 Calling method setFillColor to set the color of MyRectangle.
Setting the rectangle’s color
MyRectangle Class (Cont.)
Figure 20.13 Set and get methods for instance variable fillColor.
Get and set methods for accessing and modifying the fillColor instance variable
MyRectangle Class (Cont.)
Figure 20.14 Creating the drawMyRectangle method.
• setColor method set the color of the next object to be drawn.
Draw MyRectangle
object on JPanel
20.6 Graphics in Java
Figure 20.15 Declaring class drawJPanel.
DrawJPanel inherits from JPanel
20.6 Graphics in Java (Cont.)
Figure 20.16 Declaring instance variables.
Creating a Random object Creating a Timer object Creating an ArrayList
Array to hold
MyRectangle colors
20.6 Graphics in Java (Cont.)
Figure 20.17 Calling the superclass’s no-argument constructor.
Call the constructor of superclass
20.6 Graphics in Java (Cont.)
Figure 20.18 Starting the drawTimer object.
Start the timer
20.6 Graphics in Java (Cont.)
Figure 20.19 Creating random color and dimensions for the rectangle.
Random dimensions for the MyRectangle
20.6 Graphics in Java (Cont.)
Figure 20.20 Creating a new MyRectangle object.
20.6 Graphics in Java (Cont.)
Figure 20.21 Adding rectangle to rectangleArrayList.
Add MyRectangle object to rectangleArrayList
20.6 Graphics in Java (Cont.)
Figure 20.22 Calling the repaint method.
Call repaint method to update the JPanel
• repaint method calls the paintComponent method
20.6 Graphics in Java (Cont.)
Figure 20.23 Overriding the superclass’s paintComponent method.
Call paintComponent
method of superclass
20.6 Graphics in Java (Cont.)
Figure 20.24 Iterating through rectangleArrayList.
Draw MyRectangle
object Iterate through
rectangleArrayList
20.6 Graphics in Java (Cont.)
Figure 20.25 Declaring the clearArray method.
Creating a method to clear the
rectangleArrayList
Application
Figure 20.26 Creating a new drawJPanel object.
Set up a new
drawJPanel
Application
Figure 20.27 Calling the clear method to clear drawingJPanel.
Clearing the
rectangleArrayList
• Save the changes to your code
• Compile and run in the Command Prompt
Application (Cont.)
Figure 20.28 Completed Screen Saver application.
ScreenSaver.java (1 of 4)
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class ScreenSaver extends JFrame 8 {
9 // JButton to clear drawingJPanel 10 private JButton clearJButton;
11
12 // DrawJPanel for displaying rectangles 13 private DrawJPanel drawingJPanel;
14
15 // no-argument constructor 16 public ScreenSaver()
17 {
18 createUserInterface();
19 } 20
21 // create and position GUI components; register event handlers 22 private void createUserInterface()
23 {
24 // get content pane for attaching GUI components
ScreenSaver.java (2 of 4)
28 contentPane.setLayout( null );
29
30 // set up clearJButton
31 clearJButton = new JButton();
32 clearJButton.setBounds( 189, 16, 72, 23 );
33 clearJButton.setText( "Clear" );
34 contentPane.add( clearJButton );
35 clearJButton.addActionListener(
36
37 new ActionListener() // anonymous inner class 38 {
39 // event handler called when clearJButton is pressed 40 public void actionPerformed( ActionEvent event ) 41 {
42 clearJButtonActionPerformed( event );
43 } 44
45 } // end anonymous inner class 46
47 ); // end call to addActionListener 48
ScreenSaver.java (3 of 4)
51 drawingJPanel.setBounds( 0, 40, 450, 450 );
52 contentPane.add( drawingJPanel );
53
54 // set properties of application’s window
55 setTitle( "Screen Saver" ); // set title bar text 56 setSize( 450, 450 ); // set window size 57 setVisible( true ); // display window 58
59 } // end method createUserInterface 60
61 // clear drawingJPanel
62 private void clearJButtonActionPerformed( ActionEvent event ) 63 {
64 drawingJPanel.clear();
65
66 } // end method clearJButtonActionPerformed 67
Creating and customizing the
drawingJPanel
Clearing the
DrawJPanel
ScreenSaver.java (4 of 4)
70 {
71 ScreenSaver application = new ScreenSaver();
72 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
73
74 } // end method main 75
76 } // end class ScreenSaver
MyRectangle.java (1 of 2)
3 import java.awt.*;
4
5 public class MyRectangle extends Rectangle 6 {
7 // instance variable to hold fillColor of MyRectangle 8 private Color fillColor;
9
10 // constructor 11 public MyRectangle( int xValue, int yValue, int widthValue, 12 int heightValue, Color colorValue ) 13 {
14 // call constructor of superclass 15 super( xValue, yValue, widthValue, heightValue );
16
17 // set color of MyRectangle 18 setColor( colorValue );
19
20 } // end constructor 21
Creating an instance variable
Declaring class
MyRectangle’s constructor
MyRectangle.java (2 of 2)
24 {
25 fillColor = colorValue;
26
27 } // end method setFillColor 28
29 // get fillColor value 30 public Color getFillColor() 31 {
32 return fillColor;
33
34 } // end method getFillColor 35
36 // draw MyRectangle 37 public void draw( Graphics g )
38 {
39 g.setColor( color );
40 g.fillRect( x, y, width, height );
41
42 } // end method draw 43
44 } // end class MyRectangle
Get and set
methods for Color
instance variable
Draw MyRectangle
object on JPanel
DrawJPanel.java (1 of 4)
3 import java.awt.*;
4 import java.awt.event.*;
5 import java.util.ArrayList;
6 import java.util.Iterator;
7 import java.util.Random;
8 import javax.swing.*;
9
10 public class DrawJPanel extends JPanel 11 {
12 // Random object to create random numbers 13 private Random randomNumber = new random():
14
15 // Timer object to generate events 16 private Timer drawTimer;
17
18 // ArrayList object to hold MyRectangle objects 19 private ArrayList rectangleArrayList = new ArrayList();
20
21 // array of possible MyRectangle colors 22 private Color[] colors = { Color.BLUE, Color.ORANGE, Color.PINK, 23 Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK, 24 Color.WHITE, Color.RED, Color.GREEN };
Creating a class header Declaring
instance variable
randomNumber
DrawJPanel.java (2 of 4)
28 {
29 super();
30
31 drawTimer = new Timer( 250, 32
33 new ActionListener() // anonymous inner class 34 {
35 // event handler called every 250 microseconds 36 public void actionPerformed( ActionEvent event ) 37 {
38 drawTimerActionPerformed();
39 } 40
41 } // end anonymous inner class 42
43 ); // end call to new Timer 44
45 drawTimer.start(); // start timer 46
47 } // end constructor 48
Call constructor of superclass
Calling method
start
DrawJPanel.java (3 of 4)
51 {
52 // get random color and dimensions 53 int x = randomNumber.nextInt( 380 );
54 int y = randomNumber.nextInt( 380 );
55 int width = randomNumber.nextInt( 150 );
56 int height = randomNumber.nextInt( 150 );
57 int color = randomNumber.nextInt( 10 );
58
59 // create MyRectangle object and add it to rectangleArrayList 60 MyRectangle rectangle = new MyRectangle( x, y, width, height, 61 colors[ color ] );
62 rectangleArrayList.add( rectangle );
63
64 repaint();
65
66 } // end method drawTimerActionPerformed 67
68 // draw all rectangles 69 public void paintComponent( Graphics g ) 70 {
71 super.paintComponent( g );
72
Add rectangle object to
rectangleArrayList
Call repaint method to update JPanel
Call paintComponent
method of superclass
DrawJPanel.java (4 of 4)
75
76 MyRectangle currentRectangle; // create MyRectangle 77
78 // iterate through ArrayList and draw all MyRectangles 79 while ( rectangleIterator.hasNext() ) 80 {
81 MyRectangle currentRectangle = 82 ( MyRectangle ) rectangleIterator.next();
83
84 currentRectangle.draw( g ); // draw rectangle 85 }
86
87 } // end method paintComponent 88
89 // clear rectangleArrayList 90 public void clear() 91 {
92 rectangleArrayList.clear(); // clear ArrayList 93
94 repaint(); // repaint JPanel 95
Iterate through
rectangleArrayList
Draw MyRectangle
object
Call repaint
method to update
JPanel