ZeePedia

JAVA: How to Animate

<< Java Graphics
JAVA Applets >>
img
Web Design & Development ­ CS506
VU
Lesson 19
How to Animate?
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;
144
img
Web Design & Development ­ CS506
VU
// 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();
}
145
img
Web Design & Development ­ CS506
VU
} // 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.*;
146
img
Web Design & Development ­ CS506
VU
}// 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
147
img
Web Design & Development ­ CS506
VU
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
http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html
148