Solved

Choosing Random images

Posted on 1998-08-02
15
172 Views
Last Modified: 2010-04-16
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.
0
Comment
Question by:6100
15 Comments
 
LVL 2

Accepted Solution

by:
shchuka earned 120 total points
Comment Utility
Well, one simple solution is to create a String array with you image file names and randomly choose the index in this array.  It'll be somehting like this:

//Assume, your filenames are all in one <param>, i.e. all one string, separated by comma

String imageFilenames = getParam("imageFilenames");
java.util.StringTokenizer stk = new java.util.StringTokenizer(imageFilenames,",");

int numberOfFiles = stk.countTokens();
String[] fileNames = new String[numbefOfFiles];
for(int i=0; i<numberOfFiles; i++)
    fileNames[i] = stk.nextToken();

//Now you can choose a random filename
String randomFilename = fileNames[(int)(Math.random() * numberOfFiles)];

//And now you can load the file
Image img = loadImage(getCodeBase(),randomFilename);
0
 

Author Comment

by:6100
Comment Utility
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?



0
 

Expert Comment

by:usk
Comment Utility
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.
0
 

Expert Comment

by:usk
Comment Utility
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(...)
}





0
 

Author Comment

by:6100
Comment Utility
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?
0
 

Expert Comment

by:usk
Comment Utility
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;
}
************************************

0
 

Author Comment

by:6100
Comment Utility
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;
            }
            
      }
}

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Expert Comment

by:usk
Comment Utility
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.
}


0
 

Expert Comment

by:usk
Comment Utility
I have created an applet that draws a random image each time a key is pressed, if it is of any interest.
0
 

Author Comment

by:6100
Comment Utility
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.
0
 

Expert Comment

by:usk
Comment Utility
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

0
 

Author Comment

by:6100
Comment Utility
Adjusted points to 120
0
 

Expert Comment

by:usk
Comment Utility
Thanks !!

You gave 120 poits to "shchuka" !?

Thanks !!



0
 
LVL 7

Expert Comment

by:linda101698
Comment Utility
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
0
 

Expert Comment

by:usk
Comment Utility
Thanks :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now