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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
It looks like you have defined randomFilename as a local variable in init()
Outside init() :
String randomFilename = null;
Inside init() :
randomFilename = fileNames[(int)(Math.rando m()*number OfFiles)];
Then randomFilename will be global.
Outside init() :
String randomFilename = null;
Inside init() :
randomFilename = fileNames[(int)(Math.rando
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(...)
}
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(...)
}
ASKER
I made the changes you suggested and the applet compiled, but now it returns: java.lang.NullPointerExcep tion: 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(),you rFate);
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)==Medi aTracker.C OMPLETE)
g.drawImage(fate,11,18,thi s);
} //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;
}
************************** **********
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(),you
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)==Medi
g.drawImage(fate,11,18,thi
} //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;
}
**************************
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/wha tfate.gif" );
Image fate = getImage(getCodeBase(),you rFate);
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( imageFilen ames,"|");
int numberOfFiles = stk.countTokens();
String[] fileNames = new String[numberOfFiles];
for(int i=0; i<numberOfFiles; i++)
fileNames[i] = stk.nextToken();
fate = getImage(getCodeBase(),you rFate);
tracker.addImage(fate,1);
randomFilename = fileNames[(int)(Math.rando m() * numberOfFiles)];
}
public void paint(Graphics g)
{
tracker.waitForID(1);
if (tracker.statusID(1,true)= =MediaTrac ker.COMPLE TE)
g.drawImage(fate,11,18,thi s);
}
public boolean action(Event evt, Object event)
{
if (evt.target == tellFate)
{
//Now you can choose a random filename
fate = getImage(getCodeBase(),ran domFilenam e);
repaint();
return true;
}
else
{
fate = getImage(getCodeBase(),you rFate);
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/wha tfate.gif" );
Image fate = getImage(getCodeBase(),you rFate);
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( imageFilen ames,"|");
int numberOfFiles = stk.countTokens();
String[] fileNames = new String[numberOfFiles];
for(int i=0; i<numberOfFiles; i++)
fileNames[i] = stk.nextToken();
fate = getImage(getCodeBase(),you rFate);
tracker.addImage(fate,1);
randomFilename = fileNames[(int)(Math.rando m() * numberOfFiles)];
}
public void paint(Graphics g)
{
tracker.waitForID(1) throws InterruptedException;
if (tracker.statusID(1,true)= =MediaTrac ker.COMPLE TE)
g.drawImage(fate,11,18,thi s);
}
public boolean action(Event evt, Object event)
{
if (evt.target == tellFate)
{
//Now you can choose a random filename
fate = getImage(getCodeBase(),ran domFilenam e);
repaint();
return true;
}
else
{
fate = getImage(getCodeBase(),you rFate);
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/wha
Image fate = getImage(getCodeBase(),you
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(
int numberOfFiles = stk.countTokens();
String[] fileNames = new String[numberOfFiles];
for(int i=0; i<numberOfFiles; i++)
fileNames[i] = stk.nextToken();
fate = getImage(getCodeBase(),you
tracker.addImage(fate,1);
randomFilename = fileNames[(int)(Math.rando
}
public void paint(Graphics g)
{
tracker.waitForID(1);
if (tracker.statusID(1,true)=
g.drawImage(fate,11,18,thi
}
public boolean action(Event evt, Object event)
{
if (evt.target == tellFate)
{
//Now you can choose a random filename
fate = getImage(getCodeBase(),ran
repaint();
return true;
}
else
{
fate = getImage(getCodeBase(),you
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/wha
Image fate = getImage(getCodeBase(),you
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(
int numberOfFiles = stk.countTokens();
String[] fileNames = new String[numberOfFiles];
for(int i=0; i<numberOfFiles; i++)
fileNames[i] = stk.nextToken();
fate = getImage(getCodeBase(),you
tracker.addImage(fate,1);
randomFilename = fileNames[(int)(Math.rando
}
public void paint(Graphics g)
{
tracker.waitForID(1) throws InterruptedException;
if (tracker.statusID(1,true)=
g.drawImage(fate,11,18,thi
}
public boolean action(Event evt, Object event)
{
if (evt.target == tellFate)
{
//Now you can choose a random filename
fate = getImage(getCodeBase(),ran
repaint();
return true;
}
else
{
fate = getImage(getCodeBase(),you
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 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.
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
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
ASKER
Adjusted points to 120
Thanks !!
You gave 120 poits to "shchuka" !?
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
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 :)
ASKER
// 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/wha
Image fate = getImage(getCodeBase(),you
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(
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.rando
}
public boolean action(Event evt, Object event)
{
if (evt.target == tellFate)
{
//Now you can choose a random filename
'}' expected--> fate = getImage(getCodeBase(),ran
statement expected --> public void paint(Graphics g)
{
super.paint(g);
g.drawImage(fate,11,18,thi
}
Type expected --> return true;
}
else
{
fate = getImage(getCodeBase(),you
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(fate,11,18,thi
}
return false;
}
}
}
Also, the variable randomFilename is not recognized in the getImage() method. How can I get around this?