Link to home
Start Free TrialLog in
Avatar of 6100
6100

asked on

Choosing Random images

I want my applet to take the filenames of an a certain number of images specified in a <PARAM> tag and randomly choose one of the images to display when the user clicks the button.  I am very new to Java and programming in general, so could you please show me how to get it to work?  I have had some success with doing this with strings, but my attempts with images have so far failed.  Thank you.
ASKER CERTIFIED SOLUTION
Avatar of shchuka
shchuka

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 6100
6100

ASKER

This is what I have now.  I have tried several things, and I just get different errors.  I'm not sure how to change my code to get it to do what I want.  I get 4 errors which I will denote in the text:

// Fates.java

import java.applet.*;
import java.awt.*;
import java.lang.*;
import java.util.*;
import java.net.*;


/** Applet Fates, a teller of fates.
*  Compatible with Sun Microsystem's JDK API Version 1.0.2
*  Designed with Roaster Release 3 from Roaster Technologies, Inc.
*  @author  Scott Hays
*  @version  1.5
*/

public class Fates
extends java.applet.Applet
{
      
      
      // Creating the activation Button
      
      Button tellFate = new Button("Receive your fate!");
      
      String yourFate = new String("../media/fates/whatfate.gif");
      
      Image fate = getImage(getCodeBase(),yourFate);
      
      
      public void init()
      {
            
            // Setting a color for the background
            
            setBackground(Color.white);
            
            // Setting a Layout
            
            setLayout(new BorderLayout());
            Panel np = new Panel();
            add("North", np);
            Panel sp = new Panel();
            add("South", sp);
            
            // Adding Button "tellFate" to the applet
            
            sp.add(tellFate);
            
            
            String imageFilenames = getParameter("fates");
            java.util.StringTokenizer stk = new java.util.StringTokenizer(imageFilenames,"|");
            
            int numberOfFiles = stk.countTokens();
            String[] fileNames = new String[numberOfFiles];
            for(int i=0; i<numberOfFiles; i++)
            fileNames[i] = stk.nextToken();
            String randomFilename = fileNames[(int)(Math.random() * numberOfFiles)];
      }
      
      
      public boolean action(Event evt, Object event)
      {
            if (evt.target == tellFate)
            {
                  //Now you can choose a random filename
                  
'}' expected-->            fate = getImage(getCodeBase(),randomFilename);
statement expected -->                  public void paint(Graphics g)
                  {
                        super.paint(g);
                        g.drawImage(fate,11,18,this);
                  }
                  
Type expected -->                  return true;
            }
            else
            {
                  fate = getImage(getCodeBase(),yourFate);
                  public void paint(Graphics g)
                  {
                        super.paint(g);
                        g.drawImage(fate,11,18,this);
                  }
                  
                  return false;
            }
      }
}

Also, the variable randomFilename is not recognized in the getImage() method.  How can I get around this?



It looks like you have defined randomFilename as a local variable in init()

Outside init() :
String randomFilename = null;
Inside init()  :
randomFilename = fileNames[(int)(Math.random()*numberOfFiles)];

Then randomFilename will be global.
Do not declare paint() inside the if/else statement, call repaint(); where you have declared paint and move the declare of paint() outside the action() funktion.
repaint() will call paint(g)

public boolean action(...)
{
  if (...)
    fate = getImage(...) //select random image
  else
    fate = getImage(...)

  repaint(); // will call paint()
  return true;
}

public void paint(...)
{
  g.dtawImage(...)
}





Avatar of 6100

ASKER

I made the changes you suggested and the applet compiled, but now it returns: java.lang.NullPointerException: Trying to invoke interface method on null object.  What does this mean and how can I correct it?
1. image "fate" is not assigned anything in you init(), when the applet tryes to paint the applet the first time no image has been loaded and "fate" will be null.

2. Use MediaTracker to check that the load of the image has been completed.
*********************************

MediaTracker tracker = null;

public void init()
{
  tracker = new MediaTracker(this);
  ...
  fate = getImage(getCodeBase(),yourFate);
  tracker.addImage(fate,1); //This will load the image
}

public void paint(Graphics g)
{
  // tracker.waitAll(); // Wait until all images are loaded
  tracker.waitID(1);    // Wait until image with id 1 is loaded

  //Draw image if load complete
  if (tracker.statusID(1)==MediaTracker.COMPLETE)
   g.drawImage(fate,11,18,this);
} //End of paint

public boolean action(...)
{
  if (...)
    fate = getImage(...) //select random image
  else
    fate = getImage(...)

  //load the image if not already loaded
  tracker.addImage(fate,1);
  repaint();
  return true;
}
************************************

Avatar of 6100

ASKER

I am at my wits end!  Why does the compiler return: ';' expected tracker.waitForID(1) throws InterruptedException;?  I put ";" at the end and in the middle and it just doesn't see it.  Obviously I'm doing something else wrong, but I don't have a clue as to what it is.  

// Fates.java

import java.applet.*;
import java.awt.*;
import java.lang.*;
import java.util.*;
import java.net.*;


/** Applet Fates, a teller of fates.
*  Compatible with Sun Microsystem's JDK API Version 1.0.2
*  Designed with Roaster Release 3 from Roaster Technologies, Inc.
*  @author  Scott Hays
*  @version  1.5
*/

public class Fates
extends java.applet.Applet
{
      
      
      // Creating the activation Button
      
      Button tellFate = new Button("Receive your fate!");
      
      String yourFate = new String("../media/fates/whatfate.gif");
      
      Image fate = getImage(getCodeBase(),yourFate);
      
      String randomFilename = null;
      
      MediaTracker tracker = null;
      
      public void init()
      {
            tracker = new MediaTracker(this);
            
            // Setting a color for the background
            
            setBackground(Color.white);
            
            // Setting a Layout
            
            setLayout(new BorderLayout());
            Panel np = new Panel();
            add("North", np);
            Panel sp = new Panel();
            add("South", sp);
            
            // Adding Button "tellFate" to the applet
            
            sp.add(tellFate);
            
            
            String imageFilenames = getParameter("fates");
            java.util.StringTokenizer stk = new java.util.StringTokenizer(imageFilenames,"|");
            
            int numberOfFiles = stk.countTokens();
            String[] fileNames = new String[numberOfFiles];
            for(int i=0; i<numberOfFiles; i++)
            fileNames[i] = stk.nextToken();
            fate = getImage(getCodeBase(),yourFate);
            tracker.addImage(fate,1);
            randomFilename = fileNames[(int)(Math.random() * numberOfFiles)];
      }
      
      public void paint(Graphics g)
      {
            tracker.waitForID(1);
                  if (tracker.statusID(1,true)==MediaTracker.COMPLETE)
                  g.drawImage(fate,11,18,this);
      }
      
      public boolean action(Event evt, Object event)
      {
            
            if (evt.target == tellFate)
            {
                  //Now you can choose a random filename
                  
                  fate = getImage(getCodeBase(),randomFilename);
                  repaint();
                  
                  
                  
                  return true;
            }
            else
            {
                  fate = getImage(getCodeBase(),yourFate);
                  repaint();
                  
                  return false;
            }
            
      }
}








// Fates.java

import java.applet.*;
import java.awt.*;
import java.lang.*;
import java.util.*;
import java.net.*;


/** Applet Fates, a teller of fates.
*  Compatible with Sun Microsystem's JDK API Version 1.0.2
*  Designed with Roaster Release 3 from Roaster Technologies, Inc.
*  @author  Scott Hays
*  @version  1.5
*/

public class Fates
extends java.applet.Applet
{
      
      
      // Creating the activation Button
      
      Button tellFate = new Button("Receive your fate!");
      
      String yourFate = new String("../media/fates/whatfate.gif");
      
      Image fate = getImage(getCodeBase(),yourFate);
      
      String randomFilename = null;
      
      MediaTracker tracker = null;
      
      public void init()
      {
            tracker = new MediaTracker(this);
            
            // Setting a color for the background
            
            setBackground(Color.white);
            
            // Setting a Layout
            
            setLayout(new BorderLayout());
            Panel np = new Panel();
            add("North", np);
            Panel sp = new Panel();
            add("South", sp);
            
            // Adding Button "tellFate" to the applet
            
            sp.add(tellFate);
            
            
            String imageFilenames = getParameter("fates");
            java.util.StringTokenizer stk = new java.util.StringTokenizer(imageFilenames,"|");
            
            int numberOfFiles = stk.countTokens();
            String[] fileNames = new String[numberOfFiles];
            for(int i=0; i<numberOfFiles; i++)
            fileNames[i] = stk.nextToken();
            fate = getImage(getCodeBase(),yourFate);
            tracker.addImage(fate,1);
            randomFilename = fileNames[(int)(Math.random() * numberOfFiles)];
      }
      
      public void paint(Graphics g)
      {
            tracker.waitForID(1) throws InterruptedException;
                  if (tracker.statusID(1,true)==MediaTracker.COMPLETE)
                  g.drawImage(fate,11,18,this);
      }
      
      public boolean action(Event evt, Object event)
      {
            
            if (evt.target == tellFate)
            {
                  //Now you can choose a random filename
                  
                  fate = getImage(getCodeBase(),randomFilename);
                  repaint();
                  
                  
                  
                  return true;
            }
            else
            {
                  fate = getImage(getCodeBase(),yourFate);
                  repaint();
                  
                  return false;
            }
            
      }
}

SORRY

I forgot to tell that you must catch that Exception.
Reason is security, you don’t want it to wait for ever.

//************************************

try {
  tracker.waitForID(1);  
}
catch (InterruptedException e) {
  //Here you can do something if the exception is thrown.
}


I have created an applet that draws a random image each time a key is pressed, if it is of any interest.
Avatar of 6100

ASKER

It now compiles, but it still throws NullPointerException: Trying to invoke interface method on null object.  I would definitely be interested at seeing your applet so that I can see how an experienced person did a thing similar to me and maybe show me how to do things differently in the future.  Thanks.
I have uploaded the applet and the source code to " www.cybersite.dk/examples/ ".

If you have any doubts about how it works just comment this question and I will try to explain.

I hope this answers your questions, and in that case I would like the 100 points that you offered for this question.
 
/USK

Avatar of 6100

ASKER

Adjusted points to 120
Thanks !!

You gave 120 poits to "shchuka" !?

Thanks !!



For your future reference, when you go to grade a question, make sure that the proposed answer is by the expert you want to receive the points for your question.

If the proposed answer is not by the expert you want to receive the points, then choose the option below the question " Reopen question to other experts" and post a comment requesting that the expert you want to receive the points post an answer.

usk,
See the question in this topic area to award you points for your answer.

Linda Gardner
Customer Service @ Experts Exchange
Thanks :)