If we want to animate something like ball, moving from one place to another, we constantly need to call paintComponent( ) method and to draw the shape (ball etc.) at new place means at new coordinates.
Painting is managed by system, so calling paintComponent() directly is not recommended at all. Similarly calling paint( ) method is also not recommended. Why? Because such code may be invoked at times when it is not appropriate to paint -- for instance, before the component is visible or has access to a valid Graphics object.
Java gives us a solution in the from of repaint( ) method. Whenever we need to repaint, we call this method that in fact makes a call to paint( ) method at appropriate time.
Problem & Solution
What to do to move the shapes present in example code 18.1 (last example) when a mouse is dragged
First time painting is what we already have done
When a mouse is clicked find the co-ordinates of that place and paint Rectangle at that place by requesting, using repaint() call
Here instead of Hard-coding the position of co-ordinates uses some variables. For example mx, my – In the last example code, we draw a rectangle by passing hard-coded values like 20
g.drawRect(20,20,20,20);
– Now, we’ll use variables so that change in a variable value causes to display a rectangle at a new location
g.drawRect(mx,my,20,20;
Similarly, you have seen a tennis game (during lecture). Now, what to do code the paddle movement.
In the coming up example. We are doing it using mouse, try it using mouse. Example Code 19.1
The following outputs were produced when mouse is dragged from one location to anther
First we examine the MyPanel.java class that is drawing a filled rectangle. import javax.swing.*;import java.awt.*;
// extending class from JPanelpublic class MyPanel extends JPanel { // variables used to draw rectangles at different//locations
int mX = 20; int mY = 20;
// overriding paintComponent method public void paintComponent(Graphics g){
// erasing behaviour – this will clear all the// previous painting super.paintComponent(g); // Down casting Graphics object to Graphics2D
Graphics2D g2 = (Graphics2D)g; // changing the color to blue g2.setColor(Color.blue);
// drawing filled oval with color i.e. blue// using instance variablesg2.fillRect(mX,mY,20,20); }// end paintComponent
The Test class is given below. Additionally this class also contains the code for handling mouse events. // importing required packagesimport javax.swing.*;import java.awt.*;
public class Test { JFrame f;
// declaring Reference of MyPanel class MyPanel p;
// parameter less constructor public Test(){ f = new JFrame(); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); // instantiating reference p = new MyPanel();
// adding MyPanel into container c.add(p);
f.setSize(400,400); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // creating inner class object
Handler h = new Handler();
// registering MyPanel to handle events p.addMouseMotionListner(h); } // end constructor
// inner class used for handling events
public class Handler extends MouseMotionAdapter{ // capturing mouse dagged events
public void mouseDragged(MouseEvent me){
// getting the X-Position of mouse and assigning// value to instance variable mX of MyPanel class p.mX = me.getX();
// getting the Y-Position of mouse and assigning// value to instance variable mX of MyPanel class p.mY = me.getY();
// call to repaint causes rectangle to be drawn on// new location p.repaint() ;
} // end mouseDragged } // end Handler class // main method
public static void main(String args[ ]){ Test t = new Test();
} // end MyPanel class
On executing this program, when you drag mouse from one location to another, rectangle is also in sink with the movement of mouse. Notice that previously drawn rectangle is erased first.
If we exclude or comment out the following line from MyPanel class super.paintComponent(g);
Dragging a mouse will produce a similar kind of output shown next
Example Code 19.2: Ball Animation
The ball is continuously moving freely inside the corner of the frames. The sample outputs are shown below:
First we examine the MyPanel.java class that is drawing a filled oval. import javax.swing.*;import java.awt.*;
// extending class from JPanelpublic class MyPanel extends JPanel { // variables used to draw oval at different locations
int mX = 200; int mY = 0;
// overriding paintComponent method
public void paintComponent(Graphics g){
// erasing behaviour – this will clear all the// previous painting super.paintComponent(g); // Down casting Graphics object to Graphics2D
Graphics2D g2 = (Graphics2D)g; // changing the color to blue g2.setColor(Color.blue);
// drawing filled oval with blue color // using instance variables
}// end paintComponent } end of MyPanel class
The Test class is given below. Additionally this class also contains the code for handling mouse events. // importing required packagesimport javax.swing.*;import
java.awt.*;Import java.awt.event.*;
public class AnimTest implements ActionListener { JFrame f;
MyPanel p;
// used to control the direction of ball int x, y; public AnimTest(){ f = new JFrame(); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); x = 5; y = 3; p = new MyPanel(); c.add(p); f.setSize(400,400); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // creating a Timer class object, used for firing
// one or more action events after a specified delay // Timer class constructor requires time in
// milliseconds and object of class that handles // action events
Timer t = new Timer (5, this);
// starts the timer, causing it to start sending// action events to listeners t.start();
} // end constructor // event handler method
public void actionPerformed(ActionEvent ae){
// if ball reached to maximum width of frame minus// 40 since diameter of ball is 40 then change the// X-direction of ball
if (f.getWidth()-40 == p.mX) x = -5;
// if ball reached to maximum height of frame // minus 40 then change the Y-direction of ball if (f.getHeight()-40 == p.mY)
y = -3;
// if ball reached to min. of width of frame, // change the X-direction of ball
if (p.mX == 0 ) x = 5;
// if ball reached to min. of height of frame, // change the Y-direction of ball
if (p.mY == 0 ) y = 3;
// Assign x,y direction to MyPanel’s mX & mY p.mX += x;
p.mY += y;
// call to repaint() method so that ball is drawn on// new locations p.repaint();
} // end actionPerformed() method // main method
public static void main(String args[ ]){ AnimTest at = new AnimTest(); }
} // end of AnimTest class References:
Java, A Lab Course by Umair Javed Painting in AWT & Swing
http://java.sun.com/products/jfc/tsc/articles/painting/index.html Performing Custom Painting
Lesson 20 Applets
A small program written in Java and included in a HTML page. It is independent of the operating system on which it runs An applet is a Panel that allows interaction with a Java program
A applet is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page to tell the browser about the applet
For security reasons, applets run in a sandbox: they have no access to the client’s file system Applets Support
Most modern browsers support Java 1.4 if they have the appropriate plugin Sun provides an application appletviewerto view applets without using browser. In general you should try to write applets that can be run with any browser What an Applet is?
You write an applet by extending the class Appletor JApplet
Applet is just a class like any other; you can even use it in applications if you want When you write an applet, you are only writing part of a program
The browser supplies the main method The genealogy of Applet
The following figure shows the inheritance hierarchy of the JApplet class. This hierarchy determines much of what an applet can do and how, as you'll see on the next few pages.
java.lang.Object | +----java.awt.Component | +----java.awt.Container|+----java.awt.Panel | +----java.applet.Applet|+----javax.swing.JApplet Example Code 20.1: Writing a Simple Applet
Below is the source code for an applet called HelloApplet. This displays a “Hello World” string. Note that no main method has been provided.
// File HelloApplet.java
//step 1: importing required packagesimport java.awt.*;import javax.swing.*;
// extending class from JApplet so that our class also becomes an//appletpublic class HelloApplet extends JApplet {
// overriding paint method public void paint(Graphics g) {
// write code here u want to display & draw by using// Graphics objectg.drawString(“Hello World”, 30 , 30);
} } // end class
After defining the HelloApplet.java, the next step is to write .html file. Below is the source code of Test.html file. The Test.html contains the ordinary html code except one.
<html> <head>
<title> Simple Applet </title>
<body>
<!-- providing the class name of applet with width &height--!> <applet code="HelloApplet.class” width=150 height=100> </applet> </body> </html>
Compile & Execute
By simply double clicking on Test.html file, you can view the applet in your browser. However, you can also use the appletviewer java program for executing or running applets.
The applet viewer is invoked from the command line by the command appletviewer htmlfile
where htmlfile is the name of the file that contains the html document. For our example, the command looks like this:
appletviewer Test.html
As a result, you will see the following output
Applet Life Cycle Methods
When an applet is loaded, an instance of the applet's controlling class (an Applet subclass) is created. After that an applet passes through some stages or methods, each of them are build for specific purpose
An applet can react to major events in the following ways: It can initialize itself.
It can start running. It can stop running.
It can perform a final cleanup, in preparation for being unloaded
The applet’s life cycle methods are called in the specific order shown below. Not every applet needs to override every one of these methods.
Let’s take a look on each method in detail and find out what they do init( )
Is called only once.
The purpose of init( ) is to initialize the applet each time it's loaded (or reloaded). You can think of it as a constructor
start( )
To start the applet's execution
For example, when the applet's loaded or when the user revisits a page that contains the applet start( ) is also called whenever the browser is maximized
paint( )
paint( ) is called for the first time when the applet becomes visible Whenever applet needs to be repainted, paint( ) is called again
Do all your painting in paint( ), or in a method that is called from paint( ) stop( )
To stop the applet's execution, such as when the user leaves the applet's page or quits the browser. stop( ) is also called whenever the browser is minimized
destroy( )
Is called only once.
To perform a final cleanup in preparation for unloading Example Code 20.2: Understanding Applet Life Cycle Methods
The following code example helps you in understanding the calling sequence of applet’s life cycle methods. These methods are only displaying debugging statements on the console.
// File AppletDemo.java
//step 1: importing required packagesimport java.awt.*;import javax.swing.*;
// extending class from JApplet so that our class also becomes an//appletpublic class AppletDemo extends JApplet {
public void init ( ) {
System.out.println("init() called"); }
// overriding start method public void start ( ){
System.out.println("start() called"); }
// overriding paint method public void paint(Graphics g){
System.out.println("paint() called"); }
// overriding stop method public void stop(){
System.out.println("stop() called"); }
// overriding destroy method public void destroy(){
System.out.println("destroy() called"); }
} // end class
The DemoTest.html file is using this applet. The code snippet of it given below: <html> <head> <title> Applet Life Cycle Methods
</title></head> <body>
<!-- providing the class name of applet with width &height--!> <applet code="AppletDemo.class”
width=150 height=100> </applet></body></html>
Compile & Execute
To understand the calling sequence of applet life cycle methods, you have to execute it by using appletviewer command. Do experiments like maximizing, minimizing the applet, bringing another window in front of applet and keep an eye on console output.
Example Code 20.3: Animated Java Word Sample Output The browser output of the program is given below:
Design Process
The Program in a single call of paint method Draws string “java” on 40 random locations
For every drawing, it selects random color out of 256 * 256 * 256 RGB colors Repaint is called after every 1000 ms.
After 10 calls to repaint, screen is cleared Generating Random Numbers
Use static method random of Math class Math.random() ;
Returns positive double value greater than or equal to 0.0 or less than 1.0.
Multiply the number with appropriate scaling factor to increase the range and type cast it, if needed.
int i = (int)( Math.random() * 5 );// will generate random numbers between 0 & 4. Program’s Modules
The program is build using many custom methods. Let’s discuss each of them one by one that will help in understanding the overall logic of the program.
. drawJava( )
As name indicates, this method will be used to write String “java” on random locations. The code is given below:
// method drawJava
public void drawJava(Graphics2D g2) {
// generate first number randomly. The panel width is 1000int x = (int) (Math.random() * 1000); // generate second number randomly. The panel height is 700
int y = (int) (Math.random() * 700); // draw String on these randomly selected numebrsg2.drawString("java", x, y); }
. chooseColor( )
This method will choose color randomly out of 256 * 256 * 256 possible colors. The code snippet is given below:
// method chooseColor public Color chooseColor() {
// choosing red color value randomly int r = (int) (Math.random() * 255); // choosing green color value randomly int g = (int) (Math.random() * 255); // choosing blue color value randomly int b = (int) (Math.random() * 255);
// constructing a color by providing R-G-B valuesColor c = new Color(r, g, b); // returning color
return c; }
. chooseFont( )
This method will choose a Font for text (java) to be displayed out of 4 available fonts. The code snippet is given below:
// method chooseFont public Font chooseFont() {
// generating a random value that helps in choosing a fontint fontChoice = (int) (Math.random() * 4) + 1;
// declaring font reference Font f = null;
// using switch based logic for selecting font switch (fontChoice) {
case 1: f = new Font("Serif", Font.BOLD + Font.ITALIC, 20);break; case 2: f = new Font("SansSerif", Font.PLAIN, 17);break;
case 3: f = new Font("Monospaced", Font.ITALIC, 23);break; case 4: f = new Font("Dialog", Font.ITALIC, 30);break; } // end switch
// returns Font object return f;
} //end chooseFont . paint( )
The last method to be discussed here is paint( ). By overriding this method, we will print string “java” on 40 random locations. For every drawing, it selects random font out of 4 different fonts & random color out of 256 * 256 * 256 RGB colors.
Let’s see, how it happens: // overriding method paint
public void paint(Graphics g) {
// incrementing clear counter variable. clearCounter++;
// printing 40 “java” strings on different locations by// selcting random font & colorfor (int i = 1; i <= 40; i++) {
// choosing random color by calling chooseColor() method Color c = chooseColor();
// setting color g2.setColor(c);
// choosing random Font by calling chooseColor() method Font f = chooseFont();
g2.setFont(f);
// drawing string “java” by calling drawJava() method drawJava(g2);
} // end for loop Graphics2D g2 = (Graphics2D) g;
// checking if paint is called 10 times then clears the// screen and set counter again to zero if (clearCounter == 10) {
g2.clearRect(0, 0, 1000, 700);clearCounter = 0; } } // end paint method
Merging Pieces
By inserting all method inside JavaAnim.java class, the program will look like one given below. Notice that it contains methods discussed above with some extra code with which you are already familiar.
// File JavaAnim.java
//step 1: importing required packages import java.awt.*;
import java.awt.event.*; import javax.swing.*;
public class JavaAnim extends JApplet implements ActionListener { // used to count how many times paint is called
int clearCounter;
// declaring Timer reference Timer t;
// overriding init method, used to initialize variables public void init() {
setBackground(Color.black); clearCounter = 0;
Timer t = new Timer(1000, this); t.start();
}
// overriding paint method – discussed above public void paint(Graphics g) {
clearCounter++; Graphics2D g2 = (Graphics2D) g; if (clearCounter == 10) { g2.clearRect(0, 0, 1000, 700); clearCounter = 0; }
for (int i = 1; i <= 40; i++) { Color c = chooseColor(); g2.setColor(c); Font f = chooseFont(); g2.setFont(f); drawJava(g2); } }
// overriding actionPerformed()of ActionListener interface// called by Timer object public void actionPerformed(ActionEvent ae) {
repaint(); }
// chooseColor method – discussed above public Color chooseColor() {
int r = (int) (Math.random() * 255); int g = (int) (Math.random() * 255); int b = (int) (Math.random() * 255); Color c = new Color(r, g, b);
return c; }
// chooseFont method – discussed above public Font chooseFont() {
int fontChoice = (int) (Math.random() * 4) + 1; Font f = null;
switch (fontChoice) {
case 1: f = new Font("Serif", Font.BOLD + Font.ITALIC, 20);break; case 2: f = new Font("SansSerif", Font.PLAIN, 17);break;
case 3: f = new Font("Monospaced", Font.ITALIC, 23);break; case 4: f = new Font("Dialog", Font.ITALIC, 30);break; }
return f; }
// drawJava() method – discussed above public void drawJava(Graphics2D g2) {
int x = (int) (Math.random() * 1000); int y = (int) (Math.random() * 700); g2.drawString("java", x, y);
}
} // end class
The AnimTest.html file is using this applet. The code snippet of it given below: <html>
<head>
<title> Animated Java Word </title> </head>
<body>
<applet code="JavaAnim.class" width=1000 height=700> </applet> </body> </html>
Compile & Execute
You can execute it directly using browser or by using appletviewer application. For having fun, you can use “your name” instead of “java” and watch it in different colors ☺
References:
. Java, A Lab Course by Umair Javed . Writing Applets
Lesson 21