Solved

Choosing Random images

Posted on 1998-08-02
15
175 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
ID: 1230558
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
ID: 1230559
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
ID: 1230560
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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

Expert Comment

by:usk
ID: 1230561
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
ID: 1230562
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
ID: 1230563
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
ID: 1230564
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
 

Expert Comment

by:usk
ID: 1230565
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
ID: 1230566
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
ID: 1230567
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
ID: 1230568
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
ID: 1230569
Adjusted points to 120
0
 

Expert Comment

by:usk
ID: 1230570
Thanks !!

You gave 120 poits to "shchuka" !?

Thanks !!



0
 
LVL 7

Expert Comment

by:linda101698
ID: 1230571
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
ID: 1230572
Thanks :)
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

813 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

12 Experts available now in Live!

Get 1:1 Help Now