Bogotobogo
contact@bogotobogo.com

Bookmark and Share
Java Applet Animation Tutorial by Examples



  1. Introduction to Java Applet with Hello World
  2. Drawing - Shapes, Text, and Colors
  3. Mouse Event
  4. Keyboard Event
  5. Thread and Animation
  6. Painting
  7. 3D Graphics
  8. Sound



4. Keyboard Event

Swing components that allow the user to input text can recognise key strokes with KeyListener interface. It will pass the KeyEvent to the follwing event handler methods:

  • keyPressed(KeyEvent) : called when a key is pressed
  • keyTyped(KeyEvent): called after a key is pressed
  • keyReleased(KeyEvent) : called when a key is released


Your Ad Here

The KeyEvent object has the following methods:

  • getKeyChar(): returns the character for the key
  • getKeyCode(): returns an integer Unicode value for the key
  • getKeyText(): returns a description of the key for the key code value passed as its argument






- KeyBoardInput.java -

import java.awt.Color; import javax.swing.*; import java.awt.event.* ; public class KeyBoardInput extends JApplet implements KeyListener { JPanel pnl = new JPanel(); JTextField field = new JTextField("Type input", 30 ) ; JTextArea txtArea = new JTextArea( 5, 30 ) ; public void init() { field.addKeyListener( this ) ; // Set the applet panel to light gray pnl.setBackground(Color.LIGHT_GRAY); pnl.add( field ); //non-editable display text field txtArea.setEditable(false); pnl.add( txtArea ); add(pnl); } public void keyPressed( KeyEvent event ) { txtArea.setText("Key Pressed") ; } public void keyReleased( KeyEvent event ) { int keyCode = event.getKeyCode(); txtArea.append( "\nKey Code : " + keyCode ); txtArea.append( "\nKey Text : " + event.getKeyText(keyCode)); } public void keyTyped( KeyEvent event ) { txtArea.append("\nCharacter : " + event.getKeyChar()) ; } }




5. Thread and Animation

Java has multiple threading and it's a snap to make a new thread of execution:

Thread t = new Thread(); t.start();

Creating a new Thread object means you've launched a separate thread of execution except the the thread dies at the instant it's born. So, we are missing one key thing - the thread's job. We need a code to run by the separate thread. For multiple threading in Java, we have to look at both the thread and the job that's run by the thread.

How to launch a new thread:

  1. Make a Runnable object (the thread's job)

    Runnable threadJob = new MyRunnable();

    When we write a class that implements the Runnable interface, the class is where we will define the work that a thread will perform.

  2. Make a Thread object (the worker) and give it a Runnable (the job)

    Thread myThread = new Thread(threadJob);

    Pass the new Runnable object to the Thread constructor.

  3. Start the Thread

    myThread.start();

    Nothing happends until we call the Thread's start() method. That's when we go from having just a Thread instance to having a new thread of execution. When the new thread starts up, it takes the Runnable object's run() method.



-ClockThread.java-

import java.awt.*; import javax.swing.*; import java.util.Calendar; //To make a job for a thread, implement the Runnable interface. //Runnable is in the java.lang.package, so we don't need to import it. public class ClockThread extends JApplet implements Runnable { Thread clockThread; JTextField clockField; JPanel pnl = new JPanel(); public void init() { clockField = new JTextField("",28); Font bigFont = new Font("serif",Font.BOLD, 28); clockField.setFont(bigFont); clockField.setHorizontalAlignment(JTextField.CENTER); pnl.add(clockField); add(pnl); //Runnable object(the thread's job) is applet, this. //Make a Thread object and give it a Runnable clockThread= new Thread(this); //At this point, a Thread instance has been created //but not started yet. In other owrds, there is a Thread //object but not thread of execution //Nothing happend until we call the Thread's start() method. clockThread.start(); //When we start the thread, it moves into the runnable state. //This means the thread is ready to run and just waiting for //it's chance to be selected for execution. } // Code that will be run by the new thread. // Runnable has only one method to implement; "public void run()". // This is where we put the JOB the thread is supposed to run. public void run() { while(true) { Calendar cal = Calendar.getInstance(); String time = (cal.getTime().toString()); clockField.setText(time); try { // Put thread to sleep to make it sure that other threads get a chance to run. // When the thread wakes up, it always goes back to the runnable state // and waits for the thread scheduler to choose it to run again. Thread.sleep(500); } catch (InterruptedException e){ System.out.println(e); } } } }








-ThreeFish.java-

import java.awt.*; public class ThreeFish extends java.applet.Applet implements Runnable { int frame; int sleepTime; Thread animator; Dimension offDimension; Image offImage; Graphics offGraphics; Image underwater; Image fish, fish1,fish2; //Initialize the applet and compute the sleepTime between frames. public void init() { String str = getParameter("fps"); int fps = (str != null) ? Integer.parseInt(str) : 10; sleepTime = (fps > 0) ? (1000 / fps) : 100; underwater = getImage(getCodeBase(), "../images/java/underwater.jpg"); fish = getImage(getCodeBase(), "../images/java//fish.gif"); fish1 = getImage(getCodeBase(), "../images/java/fish1.gif"); fish2 = getImage(getCodeBase(), "../images/java//fish2.gif"); } //This method is called when the applet becomes visible on //the screen. Create a thread and start it. public void start() { animator = new Thread(this); animator.start(); } //This method is called by the thread that was created in //the start method. It does the main animation. public void run() { // Remember the starting time long tm = System.currentTimeMillis(); while (Thread.currentThread() == animator) { // Display the next frame of animation. repaint(); // sleepTime depending on how far we are behind. try { tm += sleepTime; Thread.sleep(Math.max(0, tm - System.currentTimeMillis())); } catch (InterruptedException e) { break; } // Advance the frame frame++; } } //This method is called when the applet is no longer //visible. Set the animator variable to null so that the //thread will exit before displaying the next frame. public void stop() { animator = null; offImage = null; offGraphics = null; } //Update a frame of animation. public void update(Graphics g) { Dimension d = getSize(); // Create the offscreen graphics context if ((offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height)) { offDimension = d; offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); } // Erase the previous image offGraphics.setColor(getBackground()); offGraphics.fillRect(0, 0, d.width, d.height); offGraphics.setColor(Color.black); // Paint the frame into the image paintFrame(offGraphics); // Paint the image onto the screen g.drawImage(offImage, 0, 0, null); } //Paint the previous frame (if any). public void paint(Graphics g) { update(g); } //Paint a frame of animation. public void paintFrame(Graphics g) { Dimension d = getSize(); int w = underwater.getWidth(this); int h = underwater.getHeight(this); if ((w > 0) && (h > 0)) { g.drawImage(underwater, (d.width - w)/2, (d.height - h)/2, this); } w = fish.getWidth(this); h = fish.getHeight(this); if ((w > 0) && (h > 0)) { w += d.width; //draw fish 1 g.drawImage(fish1, d.width - ((frame * 3) % w), (d.height - h)/3, this); //draw fish 0 g.drawImage(fish, d.width - ((frame * 7) % w), (d.height - h)/2, this); //draw fish 2 g.drawImage(fish2, ((frame * 5) % w), (d.height - h)/5, this); } } }





-Dukes.java-

import java.awt.*; public class Dukes extends java.applet.Applet implements Runnable { int frame; int sleepTime; Thread animator; Dimension offDimension; Image offImage; Graphics offGraphics; Image frames[]; //Initialize the applet and compute the sleepTime between frames. public void init() { String str = getParameter("fps"); int fps = (str != null) ? Integer.parseInt(str) : 10; sleepTime = (fps > 0) ? (1000 / fps) : 100; frames = new Image[10]; for (int i = 1 ; i <= 10 ; i++) { frames[i-1] = getImage(getCodeBase(), "../images/java/D" + i + ".gif"); } } //This method is called when the applet becomes visible on //the screen. Create a thread and start it. public void start() { animator = new Thread(this); animator.start(); } //This method is called by the thread that was created in //the start method. It does the main animation. public void run() { // Remember the starting time long tm = System.currentTimeMillis(); while (Thread.currentThread() == animator) { // Display the next frame of animation. repaint(); // sleepTime depending on how far we are behind. try { tm += sleepTime; Thread.sleep(Math.max(0, tm - System.currentTimeMillis())); } catch (InterruptedException e) { break; } // Advance the frame frame++; } } //This method is called when the applet is no longer //visible. Set the animator variable to null so that the //thread will exit before displaying the next frame. public void stop() { animator = null; offImage = null; offGraphics = null; } //Update a frame of animation. public void update(Graphics g) { Dimension d = getSize(); // Create the offscreen graphics context if ((offGraphics == null) || (d.width != offDimension.width) || (d.height != offDimension.height)) { offDimension = d; offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); } // Erase the previous image offGraphics.setColor(getBackground()); offGraphics.fillRect(0, 0, d.width, d.height); offGraphics.setColor(Color.black); // Paint the frame into the image paintFrame(offGraphics); // Paint the image onto the screen g.drawImage(offImage, 0, 0, null); } //Paint the previous frame (if any). public void paint(Graphics g) { update(g); } //Paint a frame of animation. public void paintFrame(Graphics g) { g.drawImage(frames[frame % 10], 0, 0, null); } }




This example is using Timer rather than Thread.sleep(delay)


-AnimatedColor.java-

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AnimatedColor extends JApplet implements ActionListener { Color startColor = Color.RED; Color endColor = Color.GREEN; Color currentColor = startColor; int animationDuration = 10000; // 10 second animation long animStartTime; MyPane myPane; @Override public void init() { Runnable myRunnable = new Runnable() { public void run() { myPane = new MyPane(); setContentPane(myPane); myPane.setBackground(Color.white); setTimer(); } }; SwingUtilities.invokeLater(myRunnable); } //Set up and start the timer public void setTimer() { //Timer(int delay, ActionListener listener) //Creates a Timer that will notify its listener, this, every delay milliseconds. Timer timer = new Timer(30, this); // initial delay while window gets set up timer.setInitialDelay(1000); // nanoTime() has 2-3ms in resolution while currentTimeMillis() has 16ms resolution. animStartTime = 1000 + System.nanoTime() / 1000000; timer.start(); } // Make your drawing widget by making a subcless of JPanel // and override one method, paintComponent(). public class MyPane extends JPanel { //Erase to the background color and fill an oval //with the current color public void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); g.setColor(getBackground()); g.setColor(currentColor); g.fillOval(w/4, h/4, w/2, h/2); } } //Callback from the Swing Timer. //Calculate the fraction elapsed //Interpolate between our start and end colors. public void actionPerformed(ActionEvent actEvt) { // calculate elapsed fraction of animation long currentTime = System.nanoTime() / 1000000; long totalTime = currentTime - animStartTime; if (totalTime > animationDuration) { animStartTime = currentTime; } float fraction = (float)totalTime / animationDuration; fraction = Math.min(1.0f, fraction); // interpolate between start and end colors with current fraction int red = (int)(fraction * endColor.getRed() + (1 - fraction) * startColor.getRed()); int green = (int)(fraction * endColor.getGreen() + (1 - fraction) * startColor.getGreen()); int blue = (int)(fraction * endColor.getBlue() + (1 - fraction) * startColor.getBlue()); // set our new color variable currentColor = new Color(red, green, blue); // force a repaint to display our oval with its new color repaint(); } }



More to come




Go back to previous Java Applet Tutorial
Go back to Top of this page
Go back to First page of Java Applet Tutorial
Go back to Java Applet Tutorial List
Go back to Java Applet Home