Friday, May 25, 2012

Simple Animations with JPanel’s Paint Method

Any instance or subclass of JPanel contains a repaint and paint method. The paint method can be used to draw content such as rectangles on to the JPanel. When you paint or draw objects on the JPanel you specify information such as the location and the width and height by means of parameters. For example to draw a rectangle you may use the syntax, graphics.drawRect(x,y, width, height);

Locations of objects are managed by having variables to describe them. The variable x, and y can store coordinates of the upper right hand point of an object we would draw/paint on the JPanel. The object location variables are important because they can be altered independantly of the rest of the panel. Changes to an object or shapes location are not displayed until paint or similar methods are called. Repainting of a JPanel can be triggered by minimizing and restoring the window that contains the JPanel.

By incrementing x or y variables the position at which a component is drawn will change. The old image is not wiped clean by the repaint or paint method implicitly. To repaint only the new image at its new location without leaving an imprint of the old one, you must repaint the background like so:
  1. Update x and y variables
  2. Repaint background
  3. Repaint the object with its new x and y values
In the following program two shapes, one rounded rectangle, and one oval are repainted to simulate movement on the computer screen. In this program sample the past images of the shapes are not removed. I did this to show you that cleaning of old drawings is not implicit with the repaint and paint method.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

 * Brian R. H.

public class MyPanel extends JPanel implements ActionListener{
 int ovalX=400,ovalY=400,ovalWidth=50,ovalHeight=30;
 int rectX = 200, rectY = 200, rectWidth = 20, rectHeight = 10;
 int rectDx=10,  rectDy=0; //change in Y
 int ovalDx=-20, ovalDy=0; 

 //        1 tick/second
 Timer clock = new Timer(1000,this);

 public void paint(Graphics g){
  //  paint occurs when the method repaint() is called (see actionPerformed method )
  Graphics2D g2d = (Graphics2D) g;
  g2d.drawRoundRect(rectX, rectY, rectWidth, rectHeight, 10, 10);
  g2d.drawOval(ovalX, ovalY, ovalWidth, ovalHeight);
 public static void main(String[] args) {
  JFrame j = new JFrame("Title");
  JPanel p = new MyPanel();
 private void updateVectors() {
 public void actionPerformed(ActionEvent arg0) {

No comments: