Animation in applets

This is a prototype of a game that I am trying to create. It is supposed to create a large rectangle then with the user pressing the space bar, shoot a little square across the screen. But it doesnt't paint the square as its going across the screen. Here is the source:
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class ShootBall extends Applet implements KeyListener
//dimensions of the rectangles
public int rect_x = -10;
public int rect_y = -10;
public int r_x = 0;
public int r_y = 0;
public int r_width = 20;
public int r_height = 10;
public int rect_width = 5;
public int rect_height = 5;
//moveable black rectangle
public Rectangle r;
static final int MIN_DELAY = 50;
public Rectangle rect;
// declare two instance variables at the head of the program
public Image dbImage;
public Graphics dbg;
// Instance variable AudioClip gun
public AudioClip gun;
//the threads that will run the different parts of the animations
public Thread th;
public int x_speed = 1;
//current background color for the applet
public Color backColor;
//this method overrides the init method from the Applet class
public void init()
// Load an audio file which is in the same directory as the class files of //the applet
gun = getAudioClip(getCodeBase(), "gun.au");
r = new Rectangle(r_x, r_y, r_width, r_height);
rect = new Rectangle(rect_x , rect_y, rect_width, rect_height);
backColor = Color.white;
addKeyListener(this);
th = new Thread();
/** Update - Method, implements double buffering */
public void update(Graphics g)
// initialize buffer
if (dbImage == null)
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
// clear screen in background
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor (getForeground());
paint (dbg);
// draw image on the screen
g.drawImage (dbImage, 0, 0, this);
//paints the rectangle at the updated position
public void paint(Graphics g)
g.setColor(Color.red);
setBackground(backColor);
g.fillRect(r_x, r_y, r_width, r_height);
g.drawRect(rect_x, rect_y, rect_width, rect_height);
//g.fillRect(rect.x, rect.y, rect.width, rect.height);
public void keyPressed(KeyEvent e)
//for this method, use the key code to generate movement
int keyCode = e.getKeyCode();
//move the rectangle
if(keyCode == KeyEvent.VK_LEFT)
r_x -= 5;
if(r_x < 0) r_x = 0;
repaint();
else if(keyCode == KeyEvent.VK_RIGHT)
r_x += 5;
if(r_x > getSize().width-r_width)
r_x = getSize().width-r_width;
repaint();
else if(keyCode == KeyEvent.VK_UP)
r_y -= 5;
if(r_y < 0) r_y = 0;
repaint();
else if(keyCode == KeyEvent.VK_DOWN)
r_y += 5;
if(r_y > getSize().height-r.height)
r_y = getSize().height-r_height;
repaint();
public void keyReleased(KeyEvent e)
Thread th = Thread.currentThread();
int key = e.getKeyCode();
// user presses left space bar
if (key == 32)
gun.play();
rect_x = r_x +20;
rect_y = r_y;
while(rect_x < 300 && Thread.currentThread() == th)
rect_x += 10;
repaint();
//update();
try
th.sleep(MIN_DELAY);
catch(InterruptedException ie) {}
public void keyTyped(KeyEvent e)
If you can find the problem please tell me,
thanks

First of all, try to make your event handlers as short as possible.
The reason why it doesn't draw anything is as follows:
- The Event thread calls your event handler
- Your event handler requests a repaint
- Your event handler doesn't return
Now you also need to know that the paint will be done only if you return from your handler :)
So you have two options:
A) use
g = getGraphics();
while () {
    paint(g); 
dispose(g);to force a repaint.
This will work, but is more or less a hack.
b) Create 2nd thread, and inside this thread do all your game stuff:
while (!gameOver) {
    if (isLeft) {
    } else if (isRight) {
    repaint();
    Thread.yield(); // or sleep
}And inside your event handler only set the isLeft, isRight variables.
For your bullets, create a small class like this:
public class Bullet {
    public Point pos;
    public Point speed;
    public Bullet(int x, int y) {
         pos = new Point(x,y);
         speed = new Point(0, -2);
    public void move() {
        pos.translate(speed.x, speed.y);
}If you want to fire a bullet, simply create a new one, and then move() all bullets in the above mentioned main loop.
Hope that helps..

Similar Messages

  • Help with creating an animated java applet...

    Hello, everyone! I'm working on a homework assignment for my Intro to Java class, and I'm having a problem I've never run into before. My assignment is to create a animated Java applet which displays an image of an alien spaceship which travels in diagonal lines across the applet area. My main problem is that when I try to compile my code, I get three "cannot find symbol" errors about my variable "alien." I can't figure out why declaring it as a class variable hasn't solved my problem. The errors pop up for the repaint() method, as well as the pane.add and the paintIcon. Here's my code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    class DrawAlien extends JPanel
    public class Alien extends JApplet implements ActionListener
      ImageIcon alien;
      public void init()
        Container pane = getContentPane();
        alien = new ImageIcon(getClass().getResource("alien.gif"));
        pane.setBackground(Color.black);
        pane.add(alien);
        Timer timer = new Timer(30, this);
        timer.start();
      public void actionPerformed(ActionEvent e)
        alien.repaint();
    }I've only posted the section which I think is relevant to my problem, but I can post the rest if anyone thinks it's necessary.
    I'm aware that the code isn't ready yet in several other ways, but I don't think I can move on until I figure out what's up with the "alien" variable. I don't need anyone to write code for me or anything like that, I just lack perspective here. A couple hints in the right direction would be invaluable. Thanks!
    Edited by: springer on Nov 25, 2007 10:46 PM

    You can?t add ImageIcon into pane, you can do like below.
    alien = new ImageIcon(getClass().getResource("alien.gif"));
        pane.setBackground(Color.black);
        JLabel label = new JLabel(alien);
        pane.add(label);

  • Flash & Applets

    I do not know if this question has been asked before, but can Applets reach the kind of graphics Flash does.
    I mean Flash is somehow more attractive then applets, and there are so many nice things that can be done with Flash. However I can not stop from saying that Action Script 2.0 (in which you code flash) is very look a like of Java Script and Java code.
    So can Java Applets come to look like Flash, and would there be a very big performance issue of so?

    I do not know if this question has been asked before,
    but can Applets reach the kind of graphics Flash
    does.Sure
    I mean Flash is somehow more attractive then applets,That's not true at all. It depends on what you want to do
    and there are so many nice things that can be done
    with Flash. However I can not stop from saying that
    Action Script 2.0 (in which you code flash) is very
    look a like of Java Script and Java code.
    So can Java Applets come to look like Flash, and
    would there be a very big performance issue of so?Flash is a tool for the artist. Flash is great because it provides rapid development tools for building presentations (i.e. graphics & animation). Applets are Java programs (which are not written by artists), which can do ANYTHING allowed by the Java API, and more. So I don't see that the two can be compared easily. But as far as graphics go, of course Java is going to be more capable, but Flash allows you to build things quickly without writing code.
    For example, say you wanted to make a simple 2D game. You'd do it in Flash, quick & easy. But what if you wanted a full-featured game? In that case, you'd have no choice but to use Java.
    Regarding performance, this has a bit to do with the implementation and use of API's and stuff. But yes, Java utilizes 2D and 3D hardware acceleration and is thus faster and more capable.

  • Filling in quadrilaterals in a pixel array

    Short version: Does anyone know of an algorithm like fillPolygon, but that works with a pixel array? (and doesn't need more than v1.1) Thanks.
    Long version:
    Hi. Hope there's a math guru among you who can give me a clue...
    I'm doing an animated 3D applet but restricted to pre-plugin Java - nothing post about 1.1. I'm double buffering for speed, with an int array [screenwidth*screenheight] for the pixels.
    At the start of each frame I want to colour in the areas where some flat rectangles (walls) are as the 'camera' sees them - quadrilaterals whose corners could be anywhere on or off the screen.
    For each line of the quadrilateral I can figure out how to find the on-screen start and end points - stopping where either the line or the screen stops, but I can't think of a fast algorithm to get from those 8 numbers per wall to a correctly filled-in pixel array.
    Thanks for your help.

    As your quadrilaterals are transformed rectangles,
    they should also be convex.
    From one vertex, with the most extreem ordiante in a
    chosen direction (eg the left-most) iterate in one
    direction (eg +ve x) along the two edges to the
    adjacent vertices using Bresenham's algorithm. That
    will give you two points with a common ordinate (eg
    (x, y0(x)) and (x, y1(x))), between which you may
    fill a line.
    On encountering another vertex, continue iterating
    along the next edge until the next vertex. When the
    furthest vertex is reached, you have filled your
    convex quadrilateral.
    Petethis approach is just fine and about as fast as you can get.
    another approach is filling the qualiteral (works as well for any convex
    polygon) by means of a triangle fan ...
    so for quadliteral with vertices A, B, C, D (each having x and y copmonents) you draw a triangle fan around a pivot point (lets say that is vertex A) like this
    drawTri (A, B, C)
    drawTri (A, C, D)
    or for a 5 vertex polygon (A, B, C, D, E)it would be
    drawTri (A, B, C)
    drawTri (A, C, D)
    drawTri (A, D, E)
    this works just as well, with a few minor advantages and disadvantages ...

  • Help needed in rendering images...ThAnkS

    I have 2 classes for rendering images. When i run the application, the images kept flashing, may i know how could i actually have 1 image appearing instead of many images flashing? In other words, i would like in a way similar to mosaic rendering process...Thanks alot
    import javax.swing.ImageIcon;
    import javax.swing.JApplet;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedInputStream;
    * TumbleItem.java requires these files:
    * SwingWorker.java
    * all the images in the images/tumble directory
    * (or, if specified in the applet tag, another directory [dir]
    * with images named T1.gif ... Tx.gif, where x is the total
    * number of images [nimgs])
    * the appropriate code to specify that the applet be executed,
    * such as the HTML code in TumbleItem.html or TumbleItem.atag,
    * or the JNLP code in TumbleItem.jnlp
    public class TumbleItem extends JApplet
    implements ActionListener {
    int loopslot = -1; //the current frame number
    String dir; //the directory relative to the codebase
    //from which the images are loaded
    javax.swing.Timer timer;
    //the timer animating the images
    int pause; //the length of the pause between revs
    int offset; //how much to offset between loops
    int off; //the current offset
    int speed; //animation speed
    int nimgs; //number of images to animate
    int width; //width of the applet's content pane
    Animator animator; //the applet's content pane
    ImageIcon imgs[]; //the images
    int maxWidth; //width of widest image
    boolean finishedLoading = false;
    JLabel statusLabel;
    static Color[] labelColor = { Color.black, Color.black,
    Color.black, Color.black,
    Color.black, Color.black,
    Color.white, Color.white,
    Color.white, Color.white };
    //Called by init.
    protected void loadAppletParameters() {
    //Get the applet parameters.
    String at = getParameter("img");
    dir = (at != null) ? at : "images/tumble";
    at = getParameter("pause");
    pause = (at != null) ? Integer.valueOf(at).intValue() : 1900;
    at = getParameter("offset");
    offset = (at != null) ? Integer.valueOf(at).intValue() : 0;
    at = getParameter("speed");
    speed = (at != null) ? (1000 / Integer.valueOf(at).intValue()) : 100;
    at = getParameter("nimgs");
    nimgs = (at != null) ? Integer.valueOf(at).intValue() : 16;
    at = getParameter("maxwidth");
    maxWidth = (at != null) ? Integer.valueOf(at).intValue() : 0;
    * Create the GUI. For thread safety, this method should
    * be invoked from the event-dispatching thread.
    private void createGUI() {
    //Animate from right to left if offset is negative.
    width = getSize().width;
    if (offset < 0) {
    off = width - maxWidth;
    //Custom component to draw the current image
    //at a particular offset.
    animator = new Animator();
    animator.setOpaque(true);
    animator.setBackground(Color.white);
    setContentPane(animator);
    //Put a "Loading Images..." label in the middle of
    //the content pane. To center the label's text in
    //the applet, put it in the center part of a
    //BorderLayout-controlled container, and center-align
    //the label's text.
    statusLabel = new JLabel("Loading Images...",
    JLabel.CENTER);
    statusLabel.setForeground(labelColor[0]);
    animator.add(statusLabel, BorderLayout.CENTER);
    //Called when this applet is loaded into the browser.
    public void init() {
    loadAppletParameters();
    //Execute a job on the event-dispatching thread:
    //creating this applet's GUI.
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.err.println("createGUI didn't successfully complete");
    //Set up the timer that will perform the animation.
    timer = new javax.swing.Timer(speed, this);
    timer.setInitialDelay(pause);
    timer.setCoalesce(false);
    timer.start(); //Start the animation.
    //Loading the images can take quite a while, so to
    //avoid staying in init() (and thus not being able
    //to show the "Loading Images..." label) we'll
    //load the images in a SwingWorker thread.
    imgs = new ImageIcon[nimgs];
    final SwingWorker worker = new SwingWorker() {
    public Object construct() {
    //Images are numbered 1 to nimgs,
    //but fill array from 0 to nimgs-1.
    for (int i = 0; i < nimgs; i++) {
    imgs[i] = loadImage(i+1);
    finishedLoading = true;
    return imgs;
    //Executes in the event-dispatching thread.
    public void finished() {
    //Remove the "Loading images" label.
    animator.removeAll();
    loopslot = -1;
    worker.start();
    //The component that actually presents the GUI.
    public class Animator extends JPanel {
    public Animator() {
    super(new BorderLayout());
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (finishedLoading &&
    (loopslot > -1) && (loopslot < nimgs)) {
    if (imgs != null && imgs[loopslot] != null) {
    imgs[loopslot].paintIcon(this, g, off, 0);
    //Update the the loopslot (frame number) and the offset.
    //If it's the last frame, restart the timer to get a long
    //pause between loops.
    public void actionPerformed(ActionEvent e) {
    loopslot++;
    if (!finishedLoading) {
    int colorIndex = loopslot % labelColor.length;
    try {
    statusLabel.setForeground(labelColor[colorIndex]);
    } catch (NullPointerException exc) {}
    return;
    if (loopslot >= nimgs) {
    loopslot = 0;
    off += offset;
    if (off < 0) {
    off = width - maxWidth;
    } else if (off + maxWidth > width) {
    off = 0;
    animator.repaint();
    if (loopslot == nimgs - 1) {
    timer.restart();
    //Called to start the applet's execution.
    public void start() {
    if (finishedLoading && (nimgs > 1)) {
    timer.restart();
    //Called to stop (temporarily or permanently) the applet's execution.
    public void stop() {
    timer.stop();
    protected ImageIcon loadImage(int imageNum) {
    String path = dir + "/Image" + imageNum + ".jpg";
    int MAX_IMAGE_SIZE = 2400; //Change this to the size of
    //your biggest image, in bytes.
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(
    this.getClass().getResourceAsStream(path));
    if (imgStream != null) {
    byte buf[] = new byte[MAX_IMAGE_SIZE];
    try {
    count = imgStream.read(buf);
    imgStream.close();
    } catch (java.io.IOException ioe) {
    System.err.println("Couldn't read stream from file: " + path);
    return null;
    if (count <= 0) {
    System.err.println("Empty file: " + path);
    return null;
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    public String getAppletInfo() {
    return "Title: TumbleItem v1.2, 23 Jul 1997\n"
    + "Author: Interactive Mosaic\n"
    + "A simple Item class to play an image loop.";
    public String[][] getParameterInfo() {
    String[][] info = {
    {"img", "string", "the directory containing the images to loop"},
    {"pause", "int", "pause between complete loops; default is 3900"},
    {"offset", "int", "offset of each image to simulate left (-) or "
    + "right (+) motion; default is 0 (no motion)"},
    {"speed", "int", "the speed at which the frames are looped; "
    + "default is 100"},
    {"nimgs", "int", "the number of images to be looped; default is 16"},
    {"maxwidth", "int", "the maximum width of any image in the loop; "
    + "default is 0"}
    return info;
    import javax.swing.SwingUtilities;
    public abstract class SwingWorker {
    private Object value; // see getValue(), setValue()
    * Class to maintain reference to current worker thread
    * under separate synchronization control.
    private static class ThreadVar {
    private Thread thread;
    ThreadVar(Thread t) { thread = t; }
    synchronized Thread get() { return thread; }
    synchronized void clear() { thread = null; }
    private ThreadVar threadVar;
    * Get the value produced by the worker thread, or null if it
    * hasn't been constructed yet.
    protected synchronized Object getValue() {
    return value;
    * Set the value produced by worker thread
    private synchronized void setValue(Object x) {
    value = x;
    * Compute the value to be returned by the <code>get</code> method.
    public abstract Object construct();
    * Called on the event dispatching thread (not on the worker thread)
    * after the <code>construct</code> method has returned.
    public void finished() {
    * A new method that interrupts the worker thread. Call this method
    * to force the worker to stop what it's doing.
    public void interrupt() {
    Thread t = threadVar.get();
    if (t != null) {
    t.interrupt();
    threadVar.clear();
    * Return the value created by the <code>construct</code> method.
    * Returns null if either the constructing thread or the current
    * thread was interrupted before a value was produced.
    * @return the value created by the <code>construct</code> method
    public Object get() {
    while (true) { 
    Thread t = threadVar.get();
    if (t == null) {
    return getValue();
    try {
    t.join();
    catch (InterruptedException e) {
    Thread.currentThread().interrupt(); // propagate
    return null;
    * Start a thread that will call the <code>construct</code> method
    * and then exit.
    public SwingWorker() {
    final Runnable doFinished = new Runnable() {
    public void run() { finished(); }
    Runnable doConstruct = new Runnable() {
    public void run() {
    try {
    setValue(construct());
    finally {
    threadVar.clear();
    SwingUtilities.invokeLater(doFinished);
    Thread t = new Thread(doConstruct);
    threadVar = new ThreadVar(t);
    * Start the worker thread.
    public void start() {
    Thread t = threadVar.get();
    if (t != null) {
    t.start();
    }

    I have 2 classes for rendering images. When i run the application, the images kept flashing, may i know how could i actually have 1 image appearing instead of many images flashing? In other words, i would like in a way similar to mosaic rendering process...Thanks alot
    import javax.swing.ImageIcon;
    import javax.swing.JApplet;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedInputStream;
    * TumbleItem.java requires these files:
    * SwingWorker.java
    * all the images in the images/tumble directory
    * (or, if specified in the applet tag, another directory [dir]
    * with images named T1.gif ... Tx.gif, where x is the total
    * number of images [nimgs])
    * the appropriate code to specify that the applet be executed,
    * such as the HTML code in TumbleItem.html or TumbleItem.atag,
    * or the JNLP code in TumbleItem.jnlp
    public class TumbleItem extends JApplet
    implements ActionListener {
    int loopslot = -1; //the current frame number
    String dir; //the directory relative to the codebase
    //from which the images are loaded
    javax.swing.Timer timer;
    //the timer animating the images
    int pause; //the length of the pause between revs
    int offset; //how much to offset between loops
    int off; //the current offset
    int speed; //animation speed
    int nimgs; //number of images to animate
    int width; //width of the applet's content pane
    Animator animator; //the applet's content pane
    ImageIcon imgs[]; //the images
    int maxWidth; //width of widest image
    boolean finishedLoading = false;
    JLabel statusLabel;
    static Color[] labelColor = { Color.black, Color.black,
    Color.black, Color.black,
    Color.black, Color.black,
    Color.white, Color.white,
    Color.white, Color.white };
    //Called by init.
    protected void loadAppletParameters() {
    //Get the applet parameters.
    String at = getParameter("img");
    dir = (at != null) ? at : "images/tumble";
    at = getParameter("pause");
    pause = (at != null) ? Integer.valueOf(at).intValue() : 1900;
    at = getParameter("offset");
    offset = (at != null) ? Integer.valueOf(at).intValue() : 0;
    at = getParameter("speed");
    speed = (at != null) ? (1000 / Integer.valueOf(at).intValue()) : 100;
    at = getParameter("nimgs");
    nimgs = (at != null) ? Integer.valueOf(at).intValue() : 16;
    at = getParameter("maxwidth");
    maxWidth = (at != null) ? Integer.valueOf(at).intValue() : 0;
    * Create the GUI. For thread safety, this method should
    * be invoked from the event-dispatching thread.
    private void createGUI() {
    //Animate from right to left if offset is negative.
    width = getSize().width;
    if (offset < 0) {
    off = width - maxWidth;
    //Custom component to draw the current image
    //at a particular offset.
    animator = new Animator();
    animator.setOpaque(true);
    animator.setBackground(Color.white);
    setContentPane(animator);
    //Put a "Loading Images..." label in the middle of
    //the content pane. To center the label's text in
    //the applet, put it in the center part of a
    //BorderLayout-controlled container, and center-align
    //the label's text.
    statusLabel = new JLabel("Loading Images...",
    JLabel.CENTER);
    statusLabel.setForeground(labelColor[0]);
    animator.add(statusLabel, BorderLayout.CENTER);
    //Called when this applet is loaded into the browser.
    public void init() {
    loadAppletParameters();
    //Execute a job on the event-dispatching thread:
    //creating this applet's GUI.
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.err.println("createGUI didn't successfully complete");
    //Set up the timer that will perform the animation.
    timer = new javax.swing.Timer(speed, this);
    timer.setInitialDelay(pause);
    timer.setCoalesce(false);
    timer.start(); //Start the animation.
    //Loading the images can take quite a while, so to
    //avoid staying in init() (and thus not being able
    //to show the "Loading Images..." label) we'll
    //load the images in a SwingWorker thread.
    imgs = new ImageIcon[nimgs];
    final SwingWorker worker = new SwingWorker() {
    public Object construct() {
    //Images are numbered 1 to nimgs,
    //but fill array from 0 to nimgs-1.
    for (int i = 0; i < nimgs; i++) {
    imgs[i] = loadImage(i+1);
    finishedLoading = true;
    return imgs;
    //Executes in the event-dispatching thread.
    public void finished() {
    //Remove the "Loading images" label.
    animator.removeAll();
    loopslot = -1;
    worker.start();
    //The component that actually presents the GUI.
    public class Animator extends JPanel {
    public Animator() {
    super(new BorderLayout());
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (finishedLoading &&
    (loopslot > -1) && (loopslot < nimgs)) {
    if (imgs != null && imgs[loopslot] != null) {
    imgs[loopslot].paintIcon(this, g, off, 0);
    //Update the the loopslot (frame number) and the offset.
    //If it's the last frame, restart the timer to get a long
    //pause between loops.
    public void actionPerformed(ActionEvent e) {
    loopslot++;
    if (!finishedLoading) {
    int colorIndex = loopslot % labelColor.length;
    try {
    statusLabel.setForeground(labelColor[colorIndex]);
    } catch (NullPointerException exc) {}
    return;
    if (loopslot >= nimgs) {
    loopslot = 0;
    off += offset;
    if (off < 0) {
    off = width - maxWidth;
    } else if (off + maxWidth > width) {
    off = 0;
    animator.repaint();
    if (loopslot == nimgs - 1) {
    timer.restart();
    //Called to start the applet's execution.
    public void start() {
    if (finishedLoading && (nimgs > 1)) {
    timer.restart();
    //Called to stop (temporarily or permanently) the applet's execution.
    public void stop() {
    timer.stop();
    protected ImageIcon loadImage(int imageNum) {
    String path = dir + "/Image" + imageNum + ".jpg";
    int MAX_IMAGE_SIZE = 2400; //Change this to the size of
    //your biggest image, in bytes.
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(
    this.getClass().getResourceAsStream(path));
    if (imgStream != null) {
    byte buf[] = new byte[MAX_IMAGE_SIZE];
    try {
    count = imgStream.read(buf);
    imgStream.close();
    } catch (java.io.IOException ioe) {
    System.err.println("Couldn't read stream from file: " + path);
    return null;
    if (count <= 0) {
    System.err.println("Empty file: " + path);
    return null;
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    public String getAppletInfo() {
    return "Title: TumbleItem v1.2, 23 Jul 1997\n"
    + "Author: Interactive Mosaic\n"
    + "A simple Item class to play an image loop.";
    public String[][] getParameterInfo() {
    String[][] info = {
    {"img", "string", "the directory containing the images to loop"},
    {"pause", "int", "pause between complete loops; default is 3900"},
    {"offset", "int", "offset of each image to simulate left (-) or "
    + "right (+) motion; default is 0 (no motion)"},
    {"speed", "int", "the speed at which the frames are looped; "
    + "default is 100"},
    {"nimgs", "int", "the number of images to be looped; default is 16"},
    {"maxwidth", "int", "the maximum width of any image in the loop; "
    + "default is 0"}
    return info;
    import javax.swing.SwingUtilities;
    public abstract class SwingWorker {
    private Object value; // see getValue(), setValue()
    * Class to maintain reference to current worker thread
    * under separate synchronization control.
    private static class ThreadVar {
    private Thread thread;
    ThreadVar(Thread t) { thread = t; }
    synchronized Thread get() { return thread; }
    synchronized void clear() { thread = null; }
    private ThreadVar threadVar;
    * Get the value produced by the worker thread, or null if it
    * hasn't been constructed yet.
    protected synchronized Object getValue() {
    return value;
    * Set the value produced by worker thread
    private synchronized void setValue(Object x) {
    value = x;
    * Compute the value to be returned by the <code>get</code> method.
    public abstract Object construct();
    * Called on the event dispatching thread (not on the worker thread)
    * after the <code>construct</code> method has returned.
    public void finished() {
    * A new method that interrupts the worker thread. Call this method
    * to force the worker to stop what it's doing.
    public void interrupt() {
    Thread t = threadVar.get();
    if (t != null) {
    t.interrupt();
    threadVar.clear();
    * Return the value created by the <code>construct</code> method.
    * Returns null if either the constructing thread or the current
    * thread was interrupted before a value was produced.
    * @return the value created by the <code>construct</code> method
    public Object get() {
    while (true) { 
    Thread t = threadVar.get();
    if (t == null) {
    return getValue();
    try {
    t.join();
    catch (InterruptedException e) {
    Thread.currentThread().interrupt(); // propagate
    return null;
    * Start a thread that will call the <code>construct</code> method
    * and then exit.
    public SwingWorker() {
    final Runnable doFinished = new Runnable() {
    public void run() { finished(); }
    Runnable doConstruct = new Runnable() {
    public void run() {
    try {
    setValue(construct());
    finally {
    threadVar.clear();
    SwingUtilities.invokeLater(doFinished);
    Thread t = new Thread(doConstruct);
    threadVar = new ThreadVar(t);
    * Start the worker thread.
    public void start() {
    Thread t = threadVar.get();
    if (t != null) {
    t.start();
    }

  • Rendering...Can anyone help???

    I have 2 classes for rendering images. When i run the application, the images kept flashing, may i know how could i actually have 1 image appearing instead of many images flashing? In other words, i would like in a way similar to mosaic rendering process...Thanks alot
    import javax.swing.ImageIcon;
    import javax.swing.JApplet;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedInputStream;
    * TumbleItem.java requires these files:
    * SwingWorker.java
    * all the images in the images/tumble directory
    * (or, if specified in the applet tag, another directory [dir]
    * with images named T1.gif ... Tx.gif, where x is the total
    * number of images [nimgs])
    * the appropriate code to specify that the applet be executed,
    * such as the HTML code in TumbleItem.html or TumbleItem.atag,
    * or the JNLP code in TumbleItem.jnlp
    public class TumbleItem extends JApplet
    implements ActionListener {
    int loopslot = -1; //the current frame number
    String dir; //the directory relative to the codebase
    //from which the images are loaded
    javax.swing.Timer timer;
    //the timer animating the images
    int pause; //the length of the pause between revs
    int offset; //how much to offset between loops
    int off; //the current offset
    int speed; //animation speed
    int nimgs; //number of images to animate
    int width; //width of the applet's content pane
    Animator animator; //the applet's content pane
    ImageIcon imgs[]; //the images
    int maxWidth; //width of widest image
    boolean finishedLoading = false;
    JLabel statusLabel;
    static Color[] labelColor = { Color.black, Color.black,
    Color.black, Color.black,
    Color.black, Color.black,
    Color.white, Color.white,
    Color.white, Color.white };
    //Called by init.
    protected void loadAppletParameters() {
    //Get the applet parameters.
    String at = getParameter("img");
    dir = (at != null) ? at : "images/tumble";
    at = getParameter("pause");
    pause = (at != null) ? Integer.valueOf(at).intValue() : 1900;
    at = getParameter("offset");
    offset = (at != null) ? Integer.valueOf(at).intValue() : 0;
    at = getParameter("speed");
    speed = (at != null) ? (1000 / Integer.valueOf(at).intValue()) : 100;
    at = getParameter("nimgs");
    nimgs = (at != null) ? Integer.valueOf(at).intValue() : 16;
    at = getParameter("maxwidth");
    maxWidth = (at != null) ? Integer.valueOf(at).intValue() : 0;
    * Create the GUI. For thread safety, this method should
    * be invoked from the event-dispatching thread.
    private void createGUI() {
    //Animate from right to left if offset is negative.
    width = getSize().width;
    if (offset < 0) {
    off = width - maxWidth;
    //Custom component to draw the current image
    //at a particular offset.
    animator = new Animator();
    animator.setOpaque(true);
    animator.setBackground(Color.white);
    setContentPane(animator);
    //Put a "Loading Images..." label in the middle of
    //the content pane. To center the label's text in
    //the applet, put it in the center part of a
    //BorderLayout-controlled container, and center-align
    //the label's text.
    statusLabel = new JLabel("Loading Images...",
    JLabel.CENTER);
    statusLabel.setForeground(labelColor[0]);
    animator.add(statusLabel, BorderLayout.CENTER);
    //Called when this applet is loaded into the browser.
    public void init() {
    loadAppletParameters();
    //Execute a job on the event-dispatching thread:
    //creating this applet's GUI.
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.err.println("createGUI didn't successfully complete");
    //Set up the timer that will perform the animation.
    timer = new javax.swing.Timer(speed, this);
    timer.setInitialDelay(pause);
    timer.setCoalesce(false);
    timer.start(); //Start the animation.
    //Loading the images can take quite a while, so to
    //avoid staying in init() (and thus not being able
    //to show the "Loading Images..." label) we'll
    //load the images in a SwingWorker thread.
    imgs = new ImageIcon[nimgs];
    final SwingWorker worker = new SwingWorker() {
    public Object construct() {
    //Images are numbered 1 to nimgs,
    //but fill array from 0 to nimgs-1.
    for (int i = 0; i < nimgs; i++) {
    imgs = loadImage(i+1);
    finishedLoading = true;
    return imgs;
    //Executes in the event-dispatching thread.
    public void finished() {
    //Remove the "Loading images" label.
    animator.removeAll();
    loopslot = -1;
    worker.start();
    //The component that actually presents the GUI.
    public class Animator extends JPanel {
    public Animator() {
    super(new BorderLayout());
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (finishedLoading &&
    (loopslot > -1) && (loopslot < nimgs)) {
    if (imgs != null && imgs[loopslot] != null) {
    imgs[loopslot].paintIcon(this, g, off, 0);
    //Update the the loopslot (frame number) and the offset.
    //If it's the last frame, restart the timer to get a long
    //pause between loops.
    public void actionPerformed(ActionEvent e) {
    loopslot++;
    if (!finishedLoading) {
    int colorIndex = loopslot % labelColor.length;
    try {
    statusLabel.setForeground(labelColor[colorIndex]);
    } catch (NullPointerException exc) {}
    return;
    if (loopslot >= nimgs) {
    loopslot = 0;
    off += offset;
    if (off < 0) {
    off = width - maxWidth;
    } else if (off + maxWidth > width) {
    off = 0;
    animator.repaint();
    if (loopslot == nimgs - 1) {
    timer.restart();
    //Called to start the applet's execution.
    public void start() {
    if (finishedLoading && (nimgs > 1)) {
    timer.restart();
    //Called to stop (temporarily or permanently) the applet's execution.
    public void stop() {
    timer.stop();
    protected ImageIcon loadImage(int imageNum) {
    String path = dir + "/Image" + imageNum + ".jpg";
    int MAX_IMAGE_SIZE = 2400; //Change this to the size of
    //your biggest image, in bytes.
    int count = 0;
    BufferedInputStream imgStream = new BufferedInputStream(
    this.getClass().getResourceAsStream(path));
    if (imgStream != null) {
    byte buf[] = new byte[MAX_IMAGE_SIZE];
    try {
    count = imgStream.read(buf);
    imgStream.close();
    } catch (java.io.IOException ioe) {
    System.err.println("Couldn't read stream from file: " + path);
    return null;
    if (count <= 0) {
    System.err.println("Empty file: " + path);
    return null;
    return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    public String getAppletInfo() {
    return "Title: TumbleItem v1.2, 23 Jul 1997\n"
    + "Author: Interactive Mosaic\n"
    + "A simple Item class to play an image loop.";
    public String[][] getParameterInfo() {
    String[][] info = {
    {"img", "string", "the directory containing the images to loop"},
    {"pause", "int", "pause between complete loops; default is 3900"},
    {"offset", "int", "offset of each image to simulate left (-) or "
    + "right (+) motion; default is 0 (no motion)"},
    {"speed", "int", "the speed at which the frames are looped; "
    + "default is 100"},
    {"nimgs", "int", "the number of images to be looped; default is 16"},
    {"maxwidth", "int", "the maximum width of any image in the loop; "
    + "default is 0"}
    return info;
    import javax.swing.SwingUtilities;
    public abstract class SwingWorker {
    private Object value; // see getValue(), setValue()
    * Class to maintain reference to current worker thread
    * under separate synchronization control.
    private static class ThreadVar {
    private Thread thread;
    ThreadVar(Thread t) { thread = t; }
    synchronized Thread get() { return thread; }
    synchronized void clear() { thread = null; }
    private ThreadVar threadVar;
    * Get the value produced by the worker thread, or null if it
    * hasn't been constructed yet.
    protected synchronized Object getValue() {
    return value;
    * Set the value produced by worker thread
    private synchronized void setValue(Object x) {
    value = x;
    * Compute the value to be returned by the <code>get</code> method.
    public abstract Object construct();
    * Called on the event dispatching thread (not on the worker thread)
    * after the <code>construct</code> method has returned.
    public void finished() {
    * A new method that interrupts the worker thread. Call this method
    * to force the worker to stop what it's doing.
    public void interrupt() {
    Thread t = threadVar.get();
    if (t != null) {
    t.interrupt();
    threadVar.clear();
    public Object get() {
    while (true) {
    Thread t = threadVar.get();
    if (t == null) {
    return getValue();
    try {
    t.join();
    catch (InterruptedException e) {
    Thread.currentThread().interrupt(); // propagate
    return null;
    * Start a thread that will call the <code>construct</code> method
    * and then exit.
    public SwingWorker() {
    final Runnable doFinished = new Runnable() {
    public void run() { finished(); }
    Runnable doConstruct = new Runnable() {
    public void run() {
    try {
    setValue(construct());
    finally {
    threadVar.clear();
    SwingUtilities.invokeLater(doFinished);
    Thread t = new Thread(doConstruct);
    threadVar = new ThreadVar(t);
    * Start the worker thread.
    public void start() {
    Thread t = threadVar.get();
    if (t != null) {
    t.start();
    }

    Nobody pays any attention to those boundries ...
    indeed many feel - and with good reason IMO - that
    the response time is better on THIS forum.I don't agree. The Swing forum is followed by several
    people who are very competent to answer Swing
    questions. Questions posted there usually receive
    good answers. Whereas this forum -- sure, people
    answer questions here too. But it is also populated
    by trolls and buffoons. And by people who don't have
    the intelligence to figure out where a question
    should be posted.
    There are obvious reasons for having thirty forums
    instead of one. I'm sure you can figure them out
    without my help. So given that there should be more
    than one forum, it follows that people should post in
    the correct forum.I better quit while I can still stand, huh ;o)
    Look I'll say it again ... I was not and am not suggesting that the camickr's point of view was wrong. I only questioned the weight that he appeared to be putting on it by outspokenly stating that swing questions ought to be posted to the swing forum only.
    There are, as you state, a lot of other more specific forums; there are AWT forums and JDBC forums, etc., but I can't remember the last time someone posted that AWT, JDBC, or whatever threads ought ONLY be posted to their respective forums. In actual fact, in many/most cases they probably should be.
    I had started a thread on - I think it was the AWT or some other forum - and found the response was not nearly so quick as it is on this forum. I'd noticed at least once that another well respected forum regular - not unlile yourself - did similarly.
    My main point was - and at this point I am sorry that I even mentioned it I think - there alot of other issues that IMO - I image from what you wrote you don't agree, but in my opinion, take precedence.
    Have a great weekend, and best regards,
    ~Bill

  • How to make smooth hardware accelerated JApplet?

    Hi there ive made a game that extends JPanel and im using the paintComponent method to do my painting
    as far as i know JPanel is hardware accelerated by default bufferStrategy(2)
    ive put the JPanel in a JFrame and the game runs very smooth with ~62fps and cpu usage is <10%
    then i tried putting the JPanel in JApplet and opened it in firefoxbrowser and the fps says ~59fps and cpu usage ~30% but its super skippy and looks like its drawing incorrectly like some of the objects are displaced very far from where they are supposed to be some frames and drawn perfectly some other frames. What's happening? Is there anyway to fix this?
    Below is some code that for a JApplet and JFrame they both contain the JPanel and ive packed everything in a jar file that can be run as a desktopapp or japplet
    I've also tried add the JApplet directly into the JFrame but it seems the performance might go down a little (though im not sure how much)
    main extends JApplet
    RobotValkyrieAttack extends JPanel
    package RobotValkyrieAttack;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class main extends JApplet{
         static LinkedList<Image> listImage;
         //no JApplet constructor is allowed to be overrriden
         public void init(){ //called by the japplet container
              this.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              this.add(r);
              Thread t = new Thread(r);
              t.start();
              this.addKeyListener(r);
         public void loadImages(){
              //images
              listImage = new LinkedList<Image>();
              listImage.add( new ImageIcon(this.getClass().getResource("data/valkyrie0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/astroid0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/clouds0.jpg")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud1.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud2.png")).getImage() );
              MediaTracker mt = new MediaTracker(this);
              for(int i=0; i<listImage.size(); i++){
                   mt.addImage(listImage.get(i),0);
              try{
                   mt.waitForAll();
              catch(Exception ex){
                   ex.printStackTrace();
         public void update(Graphics g){
              this.paint(g);
         public static void main(String args[]){
              JFrame j = new JFrame();
              j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              j.setSize(1200,700);
              j.setLocationRelativeTo(null);
              main m = new main();
              m.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              j.add(r);
              Thread t = new Thread(r);
              t.start();
              j.addKeyListener(r);
              main m = new main();
              m.init();
              j.add(m);
              j.setVisible(true);
    }

    Before we begin, note that performance of Java graphics has always been a bit 'hit and miss' in the sense that the same box with the same hardware and Java version can show radically different FPS rates if the video driver is updated.
    For better help sooner, post an SSCCE.
    Applet SSCCEs that involve images are a problem. Normally I would invite creators of image based SSCCEs to hot-link to [images available off my site|http://pscode.org/media/#image], but an applet cannot hot-link to images. It will be necessary to generate the images in code, if you want much chance of people running the code. Note that very few people will follow a link to anywhere, or download any 'build zip' or similar, to help out on a problem.
    That code snippet as posted, had a number of things that seemed horrific.
    - A class called 'main'. O_o Better would be AppletRenderTest which is not only more descriptive, but also uses the common nomenclature for a class name.
    - Frame size 1200x700?! It pays to ensure any 'comparison' of applet and application is done at the same size and my screen size is 1024x768. Make it a lot smaller, like 800x600.
    - A Swing based Timer is more typically used for Swing animation, than a Thread/Runnable.
    - GUI construction should be done on the EDT.
    - This..
    //no JApplet constructor is allowed to be overrriden..is not only factually wrong, but also incorrectly spelt.
    I am not confident you are up to writing:
    - Test code (especially test code you intend others to help with)
    - GUIs
    - Animation code
    - Applets
    Or if you are capable of parts of that, of combining the 4.
    Are you confident?

  • Ask For Help!Hurry!!

    Hi, everyone, I am a new comer of Java, now I got a problem that i need to finish the following test as soon as possible, but I have no time to do it, so please help me to finish it if you can, ok? It is very very important to me, and I know it is quite a lot questions, so just do as much as you guys could, ok? I appreciate for that seriously!
    Group A. Multiple Choice (1 Mark for each question):
         �� PLEASE CHOOSE ONLY ONE ANSWER FROM : a), b), c), d).
    A.1. The CPU, RAM, and the soundcard communicate through the:
         a) CPU Heatsink.
         b) Bus.
         c) Magnetic coil.
         d) Thyristors.
    A.2. In the early 1990, Byarne Stroustrup and James Gosling respectively introduced:
         a) Pascal and Java.
         b) Object Pascal and Java.
         c) C++ and Java.
         d) Java and C++.
    A.3. Which of the following are illegal identifier in Java?
         a) 3Input
         b) _Currency
         c) $cents
         d) Second22
    A.4. A function-type method will always:
         a) destroy an object.
         b) create a component.
         c) return a value.
         d) return itself back.
    A.4. The keyword ��void�� is only legal in:
         a) Inner-Class declaration.
         b) Method declaration.
         c) Instance variable declaration.
         d) Interface declaration.
    A.5. What is the size and range of the ��int�� primitive data type in Java?
         a) Size: 32-bit, Range: -128 to 127.
         b) Size: 32-bit, Range: 0 to 65,535.
         c) Size: 32-bit, Range: -2 Billion to +2 Billion.
         d) Size: 32-bit, Range: -1.7 Trillion to +1.7 Trillion.
    A.6. What is the size and range of the ��char�� primitive data type in Java?
         a) Size: 8-bit, Range: -128 to +127.
         b) Size: 8-bit, Range: 0 to 65,535.
         c) Size: 8-bit, Range: -2 Billion to +2 Billion.
         d) Size: 8-bit, Range: -1.7 Trillion to 1.7 Trillion.
    A.7. Which of the following is not Java keyword?
         a) abstract.
         b) for.
         c) switch.
         d) then.
    A.8. Which of the following is an illegal array declaration?
         a) int [ ] [ ] myChairs [ ];
         b) char [ ] myChairs;
         c) int [6] myChairs;
         d) char myChairs [ ];
    A.9. In Java, a ��constructor�� is used for?
         a) initializing instance variables of an object.
         b) creating a valid interface of an object.
         c) creating a duplicate class.
         d) repeating heap table.
    A.10. In Java, each object belongs to:
         a) a class.
         b) a method.
         c) an abstract class.
         d) an applet.
    A.11. Constructor name is always the same as:
         a) the first string variable name.
         b) the class name.
         c) the stack name.
         d) the statement name.
    A.12. Which is false?
         a) if ( name = = harry )
         b) if ( name = = ��harry�� )
         c) if ( name.equals(��harry��) )
         d) if ( name.equalsIgnoreCase(��harry��) )
    A.13. A Java ��interface�� is to provide a way to:
         a) approximate inheritance from 2 parents.
         b) approximate a class instance.
         c) create a new string.
         d) create random enumeration.
    A.14. Which one of the following is false:
         a) for ( int i = 1 , j = 2 ; i < 5 ; i + +, j + + )
         b) for ( int i = 1 , i < 5 ; i + + )
         c) for ( int i = 1 ; i <= 5 ; i + + )
         d) for ( int i = 1 ; i <= 10 ; i +=2 )
    A.15. To ��override�� a method is :
         a) to supply a different implement of a method that exists in the superclass.
         b) to simply change the name of a method.
         c) to supply a fresh new method that does not exists in the superclass.
         d) to supply a duplicate method.
    A.16. After executing statements in a ��try�� block, if there was no exception occur, then:
         a) ��catch�� clauses are skipped.
         b) ��catch�� clauses are executed once.
         c) ��catch�� clauses are executed twice.
         d) ��try�� block is executed again.
    A.17. Which is false in Java:
         a) arrays have fixed length.
         b) arrays have elements of a specific type.
         c) arrays use [ ] to access elements.
         d) arrays does not have a fixed length.
    A.18. Testing a program without understanding its internal structure is called:
         a) white-box testing.
         b) black-box testing.
         c) blue-box testing.
         d) regression testing.
    A.19. The default layout manager in Java is:
         a) Border layout.
         b) Flow layout.
         c) Grid layout.
         d) Card layout.
    A.20. Which of the following is false:
         a) Applet runs inside a web-browser.
         b) Applet is platform neutral.
         c) Applet can be used to create animation.
         d) Applet has a ��main�� method.
    A.21. To respond to user mouse click we need :
         a) a runnable interface.
         b) an event handler.
         c) a constructor.
         d) a string tokenizer.
    A.22. The topmost super class in Java is:
         a) This class.
         b) Object class.
         c) Container class.
         d) Java class.
    A.23. In 40 randomly-ordered items, Selection sort is much slower than:
         a) Bubble sort.
         b) Insertion sort.
         c) Quick sort.
         d) Bi-directional Bubble sort.
    A.24. A sorting algorithm with a complexity of O( nlog(n) ) is:
         a) Insertion sort.
         b) Selection sort.
         c) Quick sort.
         d) Bubble sort.
    A.25. In Java, the abstraction for enabling network communication is achieved by:
         a) Container.
         b) Socket.
         c) Frame.
         d) Template.
    A.26. Which of the following is legal for using one line to declare, construct, and initialize an array?
         a) int [ ] myList = (5,8,9);
         b) int [ ] myList = {2,3,4};
         c) int myList [ ] = [3,4,5];
         d) int [ ] myList = {2;3;4};
    A.27. Which of the following is a true statement?
         a) An abstract class is not allowed to have non-abstract methods.
         b) if a class has abstract methods, it must be declared abstract.
         c) A non-abstract class is allowed to have abstract methods.
         d) A non-abstract class is allowed to have abstract methods as long as they are also static. .
    A.28. In Object Oriented terms, if you read ��A Hotdog is a Food��, which of the following is true:
         a) Class Food extends class Hotdog.
         b) Class Hotdog extends class Food.
         c) Class Food extends class Food.
         d) Class Hotdog is in the package Food.
    A.29. Which of the following is a false statement about constructors?
         a) Constructors are not inherited.
         b) Constructors cannot be overloaded.
         c) The first statement of every constructor is a call to: super.
         d) The first statement of every constructor is a call to: this.
    A.30. Given the statement String str = ��jawbreaker��; which of the followings will return the word
         the word ��break��
         a) str.substring(3,5)
         b) str.substring(4,6)
         c) str.substring(3,8)
         d) str.substring(4,8)
    A.31. Which of the following is false statement about Java constructors?
         a) A constructor��s name must exactly match the name of the class.
         b) Constructors must not have a return type.
         c) Constructors may have a return type.
         d) If you don��t type a constructor, the Java compiler will insert a default constructor.
    A.32. Which of the following is not a Java standard layout manager?
         a) GridBagLayout.
         b) FlowLayout.
         c) GridLayout.
         d) GridCardLayout.
    A.33. In Java, multiple inheritance is implemented by:
         a) an interface.
         b) a call back function.
         c) an extension.
         d) a dummy method.
    A.34. We can shorten the statement: String word2 = new String (��Charles��); with the following:
         a) String word2 = ��Charles��;
         b) String word2 = ��Charles��;
         c) String word2 = [Charles];
         d) String word2 = {Charles};
    A.35. In Java, we can change the statement: sum = sum + 1; with the following :
         a) sum += 1; or by using: sum ++;
         b) sum =+1; or by using: sum+;
         c) sum ++ 1; or by using: sum +1;
         d) none of the above.
    A.36. A ��main�� method is found in the following:
         a) Standalone Java program.
         b) A Java Applet program.
         c) A Java constructor.
         d) A Java interface.
    A.37. In business world, large data usually stored in:
         a) Relational database system.
         b) Flat database system.
         c) Simple array database system.
         d) Single Link database system.
    A.38. To access a large relational database, we usually use:
         a) MS Access Language.
         b) Structured Query Language.
         c) Structured Quantitative Language.
         d) Structured Recursive Language.
    A.39. In method overloading we are usually:
         a) adding more arguments.
         b) adding more iterations.
         c) adding more recursions.
         d) adding more classes.
    A.40. Which sorting algorithm uses a pivot-item:
         a) Merge sort.
         b) Quick sort.
         c) Bubble sort.
         d) Selection sort.
    Group B. Find The Mistake (5 Marks for each question):
    B.1. Please indicate where the mistake is, and suggest a correction:
         import java.awt.* ;
         import hsa.Console ;
         public class BlueRect
         {     static public void  main( String [ ] args )
              {      Console c;
                   c.setColor( Color.blue ) ;
                   c.fillRect( 0,0,50,100 ) ;
    B.2. Please indicate where the mistake is, and suggest the correction:
         public class Test
              public static void main(String [ ] args)
              String [ ] names = new String();
              c.println( names [2] );     
    B.3. Please correct the following Delphi code so that it does not generate compiler error:
         procedure Tform1.Button1Click(Sender: TObject);
         var
         MyArray : array[0..8] of Integer;
         X : Integer;
         begin
              X := MyArray[3] + MyArray[8] + MyArray[9];
         end;
    B.4. Somewhere in your Java for-Loop code:
    ����.
         for (int square = 1, square <=36, square ++);
              for (int side =1, side <=4, side --)
              t.move(60);
    �� ��
    Group C. Short Questions (5 Marks for each question):
    C.1. What is a Class in Object Oriented Programming? You may use an example if you wish.
    C.2. What is the difference between = and = = in Java? You may use an example if you wish.
    C.3. Why don��t we use double numbers all the time, everywhere? Why bother with Integers?
    C.4 What are the three fundamental concepts in object-oriented programming which every Java user
    needs to understand?
    C.5 What is displayed when the following code is compiled and executed?
    String s1 = new String(��Cambridge��);
    String s2 = new String(��Cambridge��);
    if ( s1 = = s2 )
         System.out.println(��Same��);
    if ( s1.equals(s2) )
         System.out.println(��Equals��);
    Circle one of the following answer:
    a) Same
    b) Equals
    c) Same Equals
    Group D. Complete The Codes (20 Marks):
    D.1. In this program the computer user enters his/her 5 names and will get the 5 names printed on screen.
         import has.Console;
         public class MyList
         public static void main (String[ ] args)
              Console c ;
              ��������������������;
              int [ ] somelist = new int [5];
              c.println(��Enter your ������);
              for (����.. i=0; i<5; i��..) {
              somelist[i] = c.read����();
              c.println(�������������� );
         }/*end of main*/
         }/*end of MyList*/
    Group E. Describe this Program (20 Marks for this question):
    E.1. Given the following Java standalone program, please describe what will this program compute if
         you gave it the proper data. You can write your comments after each line of code. Try your best.
         Give an input and output examples.
         import has.Console;
         public class MyStuff
         public static void main (String[ ] args)
              Console c = new Console();
              int [ ] stuff = new int [5];
              c.println(��Enter your data��);
              for (int i=0; i<5; i++)
              stuff[i] = c.readInt();
              c.println(��The ����������. is �� + myFunction(stuff));
         }/*end of main*/
         public static int myFunction(int [ ] list)
              int top = list[0];
              for (int i=1; i<list.length; i++)
                   if (list[i] > top)
                   top = list;
              return top;
         }/*end of myFunction*/
         }/* end of MyStuff */

    >
    A.1. The CPU, RAM, and the soundcard communicate
    through the:
         a) CPU Heatsink.
         b) Bus.
         c) Magnetic coil.
         d) Thyristors.c
    A.2. In the early 1990, Byarne Stroustrup and James
    Gosling respectively introduced:
         a) Pascal and Java.
         b) Object Pascal and Java.
         c) C++ and Java.
         d) Java and C++. a
    A.3. Which of the following are illegal identifier in
    Java?
         a) 3Input
         b) _Currency
         c) $cents
         d) Second22c
    A.4. A function-type method will always:
         a) destroy an object.
         b) create a component.
         c) return a value.
         d) return itself back.d
    A.4. The keyword ��void�� is only legal in:
         a) Inner-Class declaration.
         b) Method declaration.
         c) Instance variable declaration.
         d) Interface declaration.d
    A.5. What is the size and range of the ��int��
    primitive data type in Java?
         a) Size: 32-bit, Range: -128 to 127.
         b) Size: 32-bit, Range: 0 to 65,535.
         c) Size: 32-bit, Range: -2 Billion to +2 Billion.
    d) Size: 32-bit, Range: -1.7 Trillion to +1.7
    Trillion.d
    A.6. What is the size and range of the ��char��
    primitive data type in Java?
         a) Size: 8-bit, Range: -128 to +127.
         b) Size: 8-bit, Range: 0 to 65,535.
         c) Size: 8-bit, Range: -2 Billion to +2 Billion.
    d) Size: 8-bit, Range: -1.7 Trillion to 1.7
    Trillion.a
    A.7. Which of the following is not Java keyword?
         a) abstract.
         b) for.
         c) switch.
         d) then.a
    A.8. Which of the following is an illegal array
    declaration?
         a) int [ ] [ ] myChairs [ ];
         b) char [ ] myChairs;
         c) int [6] myChairs;
         d) char myChairs [ ];a
    A.9. In Java, a ��constructor�� is used for?
         a) initializing instance variables of an object.
         b) creating a valid interface of an object.
         c) creating a duplicate class.
         d) repeating heap table.b
    A.10. In Java, each object belongs to:
         a) a class.
         b) a method.
         c) an abstract class.
         d) an applet.b
    A.11. Constructor name is always the same as:
         a) the first string variable name.
         b) the class name.
         c) the stack name.
         d) the statement name.d
    A.12. Which is false?
         a) if ( name = = harry )
         b) if ( name = = ��harry�� )
         c) if ( name.equals(��harry��) )
         d) if ( name.equalsIgnoreCase(��harry��) )b
    A.13. A Java ��interface�� is to provide a way to:
         a) approximate inheritance from 2 parents.
         b) approximate a class instance.
         c) create a new string.
         d) create random enumeration.b
    A.14. Which one of the following is false:
         a) for ( int i = 1 , j = 2 ; i < 5 ; i + +, j + + )
         b) for ( int i = 1 , i < 5 ; i + + )
         c) for ( int i = 1 ; i <= 5 ; i + + )
         d) for ( int i = 1 ; i <= 10 ; i +=2 )a
    A.15. To ��override�� a method is :
    a) to supply a different implement of a method that
    exists in the superclass.
         b) to simply change the name of a method.
    c) to supply a fresh new method that does not exists
    in the superclass.
         d) to supply a duplicate method.d
    A.16. After executing statements in a ��try�� block,
    if there was no exception occur, then:
         a) ��catch�� clauses are skipped.
         b) ��catch�� clauses are executed once.
         c) ��catch�� clauses are executed twice.
         d) ��try�� block is executed again. b
    A.17. Which is false in Java:
         a) arrays have fixed length.
         b) arrays have elements of a specific type.
         c) arrays use [ ] to access elements.
         d) arrays does not have a fixed length.a
    A.18. Testing a program without understanding its
    internal structure is called:
         a) white-box testing.
         b) black-box testing.
         c) blue-box testing.
         d) regression testing.d
    A.19. The default layout manager in Java is:
         a) Border layout.
         b) Flow layout.
         c) Grid layout.
         d) Card layout.b
    A.20. Which of the following is false:
         a) Applet runs inside a web-browser.
         b) Applet is platform neutral.
         c) Applet can be used to create animation.
         d) Applet has a ��main�� method.b
    A.21. To respond to user mouse click we need :
         a) a runnable interface.
         b) an event handler.
         c) a constructor.
         d) a string tokenizer.c
    A.22. The topmost super class in Java is:
         a) This class.
         b) Object class.
         c) Container class.
         d) Java class.a
    A.23. In 40 randomly-ordered items, Selection sort is
    much slower than:
         a) Bubble sort.
         b) Insertion sort.
         c) Quick sort.
         d) Bi-directional Bubble sort.b
    A.24. A sorting algorithm with a complexity of O(
    nlog(n) ) is:
         a) Insertion sort.
         b) Selection sort.
         c) Quick sort.
         d) Bubble sort.b
    A.25. In Java, the abstraction for enabling network
    communication is achieved by:
         a) Container.
         b) Socket.
         c) Frame.
         d) Template.d
    A.26. Which of the following is legal for using one
    line to declare, construct, and initialize an array?
         a) int [ ] myList = (5,8,9);
         b) int [ ] myList = {2,3,4};
         c) int myList [ ] = [3,4,5];
         d) int [ ] myList = {2;3;4};c
    A.27. Which of the following is a true statement?
    a) An abstract class is not allowed to have
    non-abstract methods.
    b) if a class has abstract methods, it must be
    declared abstract.
    c) A non-abstract class is allowed to have abstract
    methods.
    d) A non-abstract class is allowed to have abstract
    methods as long as they are also static. . a
    A.28. In Object Oriented terms, if you read ��A
    Hotdog is a Food��, which of the following is true:
         a) Class Food extends class Hotdog.
         b) Class Hotdog extends class Food.
         c) Class Food extends class Food.
         d) Class Hotdog is in the package Food.d
    A.29. Which of the following is a false statement
    about constructors?
         a) Constructors are not inherited.
         b) Constructors cannot be overloaded.
    c) The first statement of every constructor is a call
    to: super.
    d) The first statement of every constructor is a call
    to: this.a
    A.30. Given the statement String str =
    ��jawbreaker��; which of the followings will return
    the word
         the word ��break��
         a) str.substring(3,5)
         b) str.substring(4,6)
         c) str.substring(3,8)
         d) str.substring(4,8)a
    A.31. Which of the following is false statement about
    Java constructors?
    a) A constructor��s name must exactly match the name
    of the class.
         b) Constructors must not have a return type.
         c) Constructors may have a return type.
    d) If you don��t type a constructor, the Java
    compiler will insert a default constructor.d
    A.32. Which of the following is not a Java standard
    layout manager?
         a) GridBagLayout.
         b) FlowLayout.
         c) GridLayout.
         d) GridCardLayout.a
    A.33. In Java, multiple inheritance is implemented
    by:
         a) an interface.
         b) a call back function.
         c) an extension.
         d) a dummy method.c
    A.34. We can shorten the statement: String word2 =
    new String (��Charles��); with the following:
         a) String word2 = ��Charles��;
         b) String word2 = ��Charles��;
         c) String word2 = [Charles];
         d) String word2 = {Charles};d
    A.35. In Java, we can change the statement: sum =
    sum + 1; with the following :
         a) sum += 1; or by using: sum ++;
         b) sum =+1; or by using: sum+;
         c) sum ++ 1; or by using: sum +1;
         d) none of the above.c
    A.36. A ��main�� method is found in the following:
         a) Standalone Java program.
         b) A Java Applet program.
         c) A Java constructor.
         d) A Java interface.c
    A.37. In business world, large data usually stored
    in:
         a) Relational database system.
         b) Flat database system.
         c) Simple array database system.
         d) Single Link database system.d
    A.38. To access a large relational database, we
    usually use:
         a) MS Access Language.
         b) Structured Query Language.
         c) Structured Quantitative Language.
         d) Structured Recursive Language. a
    A.39. In method overloading we are usually:
         a) adding more arguments.
         b) adding more iterations.
         c) adding more recursions.
         d) adding more classes.b
    A.40. Which sorting algorithm uses a pivot-item:
         a) Merge sort.
         b) Quick sort.
         c) Bubble sort.
         d) Selection sort.b
    Group B. Find The Mistake (5 Marks for each
    question):
    B.1. Please indicate where the mistake is, and suggest
    a correction:
         import java.awt.* ;
         import hsa.Console ;
         public class BlueRect
         {     static public void  main( String [ ] args )
              {      Console c;
                   c.setColor( Color.blue ) ;
                   c.fillRect( 0,0,50,100 ) ;
         }"static public" should be "public static". it's reversed.
    B.2. Please indicate where the mistake is, and suggest
    the correction:
         public class Test
              public static void main(String [ ] args)
              String [ ] names = new String();
              c.println( names [2] );     
         } When declaring an array, do not put a space between the brackets. It should be "String[]".
    B.3. Please correct the following Delphi code so that
    it does not generate compiler error:
         procedure Tform1.Button1Click(Sender: TObject);
         var
         MyArray : array[0..8] of Integer;
         X : Integer;
         begin
              X := MyArray[3] + MyArray[8] + MyArray[9];
         end;
    B.4. Somewhere in your Java for-Loop code:
    ����.
         for (int square = 1, square <=36, square ++);
              for (int side =1, side <=4, side --)
              t.move(60);
    �� �� The object "t" was never declared or initialized. You probably need the following line:
    Turtle t = new Turtle();
    Group C. Short Questions (5 Marks for each question):
    C.1. What is a Class in Object Oriented Programming?
    You may use an example if you wish.A class describes what your program can do. For example:
    class FileCopier {
    // put code here
    C.2. What is the difference between = and = =
    in Java? You may use an example if you wish.= is for bitwise comparison, while == is for value comparison
    C.3. Why don��t we use double numbers all the time,
    everywhere? Why bother with Integers?An Integer is an object. Sometimes you need to store a number in a Vector; in this case, having an object is ideal.
    C.4 What are the three fundamental concepts in
    object-oriented programming which every Java user
    needs to understand?Hiding information, hierarchy, member variables.
    C.5 What is displayed when the following code is
    compiled and executed?
    String s1 = new String(��Cambridge��);
    String s2 = new String(��Cambridge��);
    if ( s1 = = s2 )
         System.out.println(��Same��);
    if ( s1.equals(s2) )
         System.out.println(��Equals��);
    Circle one of the following answer:
    a) Same
    b) Equals
    c) Same Equals b
    Group D. Complete The Codes (20 Marks):
    D.1. In this program the computer user enters
    his/her 5 names and will get the 5 names printed on
    screen.
         import has.Console;
         public class MyList
         public static void main (String[ ] args)
              Console c ;
              ��������������������;
              int [ ] somelist = new int [5];
              c.println(��Enter your ������);
              for (����.. i=0; i<5; i��..) {
              somelist[i] = c.read����();
              c.println(�������������� );
         }/*end of main*/
         }/*end of MyList*/
    Group E. Describe this Program (20 Marks for this
    question):
    E.1. Given the following Java standalone program,
    please describe what will this program compute if
    you gave it the proper data. You can write your
    comments after each line of code. Try your best.
         Give an input and output examples.
         import has.Console;
         public class MyStuff
         public static void main (String[ ] args)
              Console c = new Console();
              int [ ] stuff = new int [5];
              c.println(��Enter your data��);
              for (int i=0; i<5; i++)
              stuff[i] = c.readInt();
    c.println(��The ����������. is �� +
    + myFunction(stuff));
         }/*end of main*/
         public static int myFunction(int [ ] list)
              int top = list[0];
              for (int i=1; i<list.length; i++)
                   if (list[i] > top)
                   top = list;
              return top;
         }/*end of myFunction*/
         }/* end of MyStuff */
    The program asks the user to enter 5 numbers. Then, it checks which number is greater than 0, and prints that number.

  • SSRS MHTML formatting problem when using gmail

    Hi,
    I have several reports on my SSRS report server 2008 R2. All display great and subscriptions as MHTML display great too.
    But when the email is viewed on gmail report display do not keep any formatting and look out of shape.
    and it is fine for outllok,mozilla,IE.
    please help me to resolve this issue for gmail.
    thanks.

    Hi BI_group,
    From the "Browser Support" section of the
    Rendering to HTML article, we can see that HTML rendering extension supports the following browser versions: Internet Explorer 5.5 and later, Firefox 1.5 and later, Safari 3.0 and later.
    MHTML, short for MIME HTML, is a web page archive format used to combine resources that are typically represented by external links (such as images, Flash animations, Java applets, and audio files) with HTML code into a single file.
    So, as per my understanding, the issue occurs due to the factor that the MHTML rendering format is not supported perfectly by gmail. And from
    HTML Device Information Settings document, we can know that there is no such property that support gmailcompat. So we couldn’t fix this issue at this moment, this is by design.
    Thank you for your understanding.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Email and default browser

    When I click through an email (I use Outlook 2010) Internet Explorer sometimes opens although Firefox is my default browser. I have made sure that Firefox has all it's defaults, but IE has kept .mht, and .mhtml and won't let me change it. I don't know what these 2 formats are, but is there anything I can do to make sure that Firefox opens all email?

    .mht is a  web page archive saved with Internet Explorer; formatted using MIME HTML or "MHTML," 
    .mhtml is a web page archive format used to combine resources that are typically represented by external links (such as im
    ages, Flash animations, Java applets, audio files) together with HTML code into a single file.
    You can set the associations for .mht and .mhtml files to Firefox by changing the program associated with it. 
    As you can see in the following image the associations for both on this desktop PC with Windows 7 are set to Internet Explorer. 
    I did not quite understand your very last sentence. Did you mean to say change the default program that opens html links in your emails?
    I have Google Chrome set as the default browser to open any .htm and html files. That is how I make certain that Google Chrome opens URLs  or html documents (or attachments)that I  choose to click on in Outlook 2010 emails.
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • Could you please tell me how to play sounds?

    What is the class I should import (I am using IE5.5).

    import java.applet.Applet;
    import java.awt.event.*;
    import java.awt.Graphics;
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.Image;
    import java.awt.image.*;
    import sun.audio.*;
    import java.applet.AudioClip;
    public class Animation extends Applet implements Runnable {
    Thread animationThread = null;
    protected int cycles = 0;
    Image frame[] = new Image[10];
    int cur = 0;
    AudioClip sound = null;
    public void init() {
    resize(35,35);
    String cyclesTemp = getParameter("CYCLES");
    if (cyclesTemp != null)
    cycles = Integer.valueOf(cyclesTemp).intValue();
    for(int i = 0; i < 10; i++)
    frame[i] = getImage(getCodeBase(),"frame"+i+".gif");
    sound = this.getAudioClip(getCodeBase(),"Sound.au");
    public void start() {
    animationThread = new Thread(this);
    animationThread.start();
    public void run() {
    while(true){
    this.sound.play();
    cur++;
    try{
    repaint();
    Thread.sleep(1000);
    }catch(Exception e){}
    if(cur==10) cur=0;
    public void paint(Graphics g) {
    g.drawImage(frame[cur], 100, 50,this);
    public void mouseDown(int x, int y) {
    animationThread = new Thread(this);
    animationThread.start();

  • Microsoft JScript compilation error alert on initial load using IE7

    I have noticed that a javascript alert window is displayed whenever an Applet is initially launched using IE7.
    This does not happen using IE8 (or FF, SF, Chrome, etc).
    I thought it was our implementation, but the alert is also shown launching any Applet from the following;
    http://java.sun.com/applets/jdk/
    There are typically 2 alerts and after pressing OK, the Applets appear to run successfully.
    The specific error is;
    Alert title: Microsoft JScript compilation error.
    Alert content: Expected ')' in regular expression.
    I don't always remember this error using IE7.
    Maybe it's related to the JRE?
    I am currently using: (build 1.6.0_26-b03)
    Any solution out there?

    879129 wrote:
    ..I thought it was our implementation, but the alert is also shown launching any Applet from the following;
    http://java.sun.com/applets/jdk/
    I just had a look at the source of two of the pages from the 1.4 section of that page (Animator (1) & ArcTest) & saw some very questionable HTML for the <tt>applet</tt> element, as well as two seemingly unrelated scripts. What do you get for (instead of those), the GIF Animator (the applet form)? It uses <tt>deployJava.js</tt>, which is about the only deployment option that Oracle cares about at the moment.

  • Viewing .doc file (saved as .doc from .mht) on ipad

    Hi
    My requirement is
    I have a .doc document, which i saved as .doc from .mht format, i am able to open that file on a PC, but where as if i try to view the same on iPad i am not able to do so,
    Is there any way of converting a doc file which is based on .mht to iPad compatible doc? or can i convert it to dsiplay on iPad.
    Please advice.
    Thank you very much
    Regards
    Chaitanya.A

    What apps are you using to try to display the file?
    My understanding of mht is:
    MHTML, short for MIME HTML, is a web page archive format used to combine resources that are typically represented by external links (such as images, Flash animations, Java applets, audio files) together with HTML code into a single file.
    http://en.wikipedia.org/wiki/MHTML
    Can't you copy the web page to one of your servers?
    You could try saving the page in firefox.  It leaves the page in as one file and a folder of all the included files.  You can forget about viewing flash.
    Robert

  • How do I use a Frame to set up an applet animation?

    I am working on this program for a physics class. It is supposed to be an applet which animates a spring. I first set the animation with dummy values and it works fine (aside from a little flicker). I set up a frame which pops up and allows a user to input values. The frame looks and collects the information as I wanted; now I am trying to get these values passed to the init() method of my applet to be the basis of the animation. I was thinking something like JOptionPane; but, I wanted it to be more customized.
    This is the inner class in Launcher which prepares information and disposes the frame. I would like to pass this array
    "out."
         private class Exe implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   String execute = event.getActionCommand();
                   if (execute == "Ok"){
                        out = new double[5];
                        for(int c = 0; c < 5; c++){
                             out[c] = Double.parseDouble(input[c].getText());}
                        dispose();}}}}This is the init() method which sets up all the information required for the animation. I want to receive the array here:
    public class Spring extends Applet implements Runnable{
         double t = 0;
         double x,v,a,k;
         int s;
         int delay;
         Thread animator;
         double mass, omega, phi,gravity,equilibrium,amplitude, positionI, velocityI, phiHat;
         double scaler;
         Panel buttons;
         Button start;
         Button pause;
         Button back;
         Button forward;
         Button stop;
         Button restart;     
         Frame l;
         public void init(){
              //Opens the menu which allows user inputs
              l = new Launcher();
              l.setSize(500,450);
              l.setVisible(true);
              //Sets the ammount of time the system waits to refresh
              //Smaller numbers create a more accurate picture
              //This is in milliseconds
              delay = 100;
              //Calculates info about the system
              mass = 5;
              equilibrium = .5;
              gravity = 9.8;
              k = (mass * gravity)/equilibrium;
              omega = Math.pow(k/mass,.5);
              //Differential Equation
              positionI = .1;
              velocityI = -.1;
              amplitude = Math.pow(Math.pow((positionI/Math.cos(omega*0)),2)+
                        Math.pow((velocityI/(omega*Math.cos(omega*0))),2),.5);
              phiHat = Math.abs(Math.atan((positionI/Math.cos(omega*0))/(velocityI/(omega*Math.cos(omega*0)))));
              if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                   phi = phiHat;}
              if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                   phi = Math.PI + phiHat;}
              if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                   phi = (2*Math.PI) - phiHat;}
              if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                   phi = Math.PI - phiHat;}
              //scales the spring to the animation grid
              if (amplitude !=  0)
                   scaler = amplitude / 105;
              else
                   scaler = 1;
              //Adds buttons to applet          
              buttons = new Panel();
              buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
              start = new Button("Start");
              buttons.add(start);
              pause = new Button("Pause");
              buttons.add(pause);
              back = new Button("Back");
              buttons.add(back);
              forward = new Button("Forward");
              buttons.add(forward);
              stop = new Button("Stop");
              buttons.add(stop);
              restart = new Button("Restart");
              buttons.add(restart);
              this.setLayout(new BorderLayout());
              add(buttons, BorderLayout.SOUTH);}

    I was trying to tweak my animation and I have ran into some problems:
    To refresh, I have an applet which animates a spring. The equation which drives the animation is taken from user input which is entered in a frame that launches when the applet loads. The user has the option to control the animation with buttons as opposed to the applet running itself. Anyway, everything worked fine until I rewrote the applet with an image buffer. Now, the frame launches and is automatically placed in the background (on the desktop). The start, stop, and pause buttons work; but the step back and forward buttons do not work. If you have time to offer suggestions they would be appreciated.
    Set Up Buttons and Frame:
         public void init(){
              l = new Frame("Information About Your Spring");
              l.setLayout(new GridLayout(4,1));
              directions = new TextArea(text);
              directions.setEditable(false);
              l.add(directions);
              GravityHandler a = new GravityHandler();
              gravityButtons = new Container();
              gravityButtons.setLayout(new GridLayout(bodies.length/4,4));
              gravityL = new JRadioButton[bodies.length];
              g = new ButtonGroup();
              for(int x = 0; x < bodies.length; x++){
                   if(bodies[x].equals("Earth")){
                        gravityL[x] = new JRadioButton(bodies[x], true);
                        gravityL[x].addActionListener(a);}
                   else{
                        gravityL[x] = new JRadioButton(bodies[x], false);
                        gravityL[x].addActionListener(a);}
                   g.add(gravityL[x]);
                   gravityButtons.add(gravityL[x]);}
              l.add(gravityButtons);
              lables = new TextField[5];
              input = new TextField[5];
              otherInput = new Container();
              otherInput.setLayout(new GridLayout(3,4,5,5));
              lables[0] = new TextField("Mass:");
              lables[0].setEditable(false);
              otherInput.add(lables[0]);
              input[0] = new TextField(20);
              otherInput.add(input[0]);
              lables[1] = new TextField("Gravity:");
              lables[1].setEditable(false);
              otherInput.add(lables[1]);
              input[1] = new TextField("9.81",20);
              input[1].setEditable(false);
              otherInput.add(input[1]);
              lables[2] = new TextField("Equilibrium:");
              lables[2].setEditable(false);
              otherInput.add(lables[2]);
              input[2] = new TextField(20);
              otherInput.add(input[2]);
              lables[3] = new TextField("Displacement:");
              lables[3].setEditable(false);
              otherInput.add(lables[3]);
              input[3] = new TextField(20);
              otherInput.add(input[3]);
              lables[4] = new TextField("Initial Velocity:");
              lables[4].setEditable(false);
              otherInput.add(lables[4]);
              input[4] = new TextField(20);
              otherInput.add(input[4]);
              l.add(otherInput);
              Exe now = new Exe();
              buttonPlace = new Container();
              buttonPlace.setLayout(new FlowLayout(FlowLayout.CENTER));
              Ok = new Button("Ok");
              Ok.addActionListener(now);
              buttonPlace.add(Ok);
              l.add(buttonPlace);
              l.setSize(425,500);
              l.setResizable(false);
              l.toFront();
              l.setVisible(true);
              delay = 100;
              buttons = new Panel();
              buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
              start = new Button("Start");
              buttons.add(start);
              pause = new Button("Pause");
              buttons.add(pause);
              back = new Button("Back");
              buttons.add(back);
              forward = new Button("Forward");
              buttons.add(forward);
              stop = new Button("Stop");
              buttons.add(stop);
              restart = new Button("Restart");
              buttons.add(restart);
              this.setLayout(new BorderLayout());
              add(buttons, BorderLayout.SOUTH);
              display = createImage(size().width, size().height);
              dspl = display.getGraphics();
              l.toFront();}The frame is handled by ActionListener
    Action based on the buttons:
         public boolean action(Event e, Object args){
              if (e.target == start){
                   animator = new Thread(this);
                   animator.start();}
              if (e.target == stop){
                   animator.stop();
                   animator = null;
                   t = 0;
                   repaint();}
              if (e.target == pause){
                   animator.stop();
                   animator = null;}
              if (e.target == restart){
                   animator.stop();
                   animator = null;
                   t = 0;
                   repaint();
                   animator = new Thread(this);
                   animator.start();}
              if (e.target == back){
                   animator.stop();
                   animator = null;
                   t -= .1;
                   repaint();}
              if (e.target == forward){
                   animator.stop();
                   animator = null;
                   t += .1;
                   repaint();}
              return true;}
    draw animation:
         public void run(){
              while(Thread.currentThread() == animator){
                   try{
                        Thread.sleep(delay);}
                   catch(InterruptedException e){}
                   if(animator != null){
                        t+= .1;}
                   else{
                        repaint();}     
                   dspl.setColor(Color.black);
                   dspl.fillRect(0,0,size().width,size().height);
                   dspl.setColor(Color.white);
                   k = (mass * gravity)/equilibrium;
                   omega = Math.pow(k/mass,.5);
                   amplitude = Math.pow(Math.pow((positionI/Math.cos(omega*0)),2)+
                             Math.pow((velocityI/(omega*Math.cos(omega*0))),2),.5);
                   phiHat = Math.abs(Math.atan((positionI/Math.cos(omega*0))/(velocityI/(omega*Math.cos(omega*0)))));
                   if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                        phi = phiHat;}
                   if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                        phi = Math.PI + phiHat;}
                   if((positionI/Math.cos(omega*0)) < 0 && (velocityI/(omega*Math.cos(omega*0))) > 0){
                        phi = (2*Math.PI) - phiHat;}
                   if((positionI/Math.cos(omega*0)) > 0 && (velocityI/(omega*Math.cos(omega*0))) < 0){
                        phi = Math.PI - phiHat;}
                   if (amplitude !=  0)
                        scaler = amplitude / 105;
                   else
                        scaler = 1;
                   dspl.drawRect(5, 5, 442, 240);
                   dspl.drawLine(200,5,200,245);
                   dspl.drawLine(200,120,447,120);
                   dspl.drawLine(20,20, 20, 230);
                   dspl.drawLine(20, 20, 24, 20);
                   dspl.drawString( String.format("%.2f m", amplitude) , 24,21);
                   dspl.drawLine(20, 230, 24, 230);
                   dspl.drawString( String.format("%.2f m", amplitude) , 24,231);
                   dspl.drawLine(20, 125, 24, 125);
                   dspl.drawString( "0 m", 24, 126);
                   x = amplitude*Math.sin((omega*t)+phi); //Calculate position
                   v = (amplitude*omega)*Math.cos((omega*t)+phi); //Calculate velovity
                   a = -(Math.pow(omega,2)*amplitude)*Math.sin((omega*t)+phi); //Calculate acceleration
                   dspl.drawString("Kinematics:", 210,20);
                   dspl.drawString(String.format("Time: %.1f Seconds",t), 210, 40);
                   dspl.drawString(String.format("Position: %.2f m",x), 210,60 );
                   dspl.drawString(String.format("Velocity: %.2f m/s",v), 210,80 );
                   dspl.drawString(String.format("Acceleration: %.2f m/sec sq",a),210,100 );
                   dspl.drawString("Atributes:", 210, 140);
                   dspl.drawString(String.format("Equation: x(t) = %.2fsin(%.2ft + %.3f)",amplitude,omega,phi),210,160);
                   dspl.drawString(String.format("Spring Constant: %.2f n/m",k),210,180);
                   dspl.drawString(String.format("Period: %.2f Seconds", (2*Math.PI)/omega), 210,200);
                   dspl.drawString(String.format("Frequency: %.2f Hz",omega/(2*Math.PI)),210,220);
                   dspl.drawString(String.format("Amplitude: %.2f",amplitude),210,240);
                   s = (int) (x/scaler + 126);
                   dspl.drawLine(128,5,128,s-12);
                   dspl.drawString(String.format("%.0f kg Mass",mass), 104, s);
                   repaint();}}
         public void update(Graphics g){
              paint(g);}
         public void paint(Graphics g){
              g.drawImage(display,0,0,this);}Thanks

  • Applet Parameters For Animated Gif Using AWT

    I need to have my applet except parameters to change from one type of animated gif (dog) to another animated gif (cat). There are two for each animal. If the animal parameter is "dog" the dog1.gif and the dog2.gif will be used for the animation. I'm not too sure on how to go about this.
    private String sDog;
    private String sCat;
    sDog = getParameter("");
    if (sDog.equalsIgnoreCase("dog"))
    How do I add both gifs in the control statement?
    Thanks so much,
    Jeff

    private String sDog;
    private String sCat;
    sDog = getParameter("dog");
    for(int i=1;i<3;i++){
    if (sDog.equalsIgnoreCase("dog" i".gif"))
    //code to display the gif
    remember your parameter should be <b>dog</b>

Maybe you are looking for