How to Make Image Appear Randomly Every X Seconds in Java Using Timer

How can I make image appear randomly every x seconds in java using timer?

"How can I use a timer to do this every x seconds when the app is openend?"

Have a look at this example. I gathered Images from the internet, but you can do the same using image files. What I did was use an array of URL and BufferedImage and got a random index ever 500 milliseconds and repaint() the panel

Note If you are going to use image files, you may want to look at this answer also.

Sample Image

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestImageRotate {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
JFrame frame = new JFrame("Image Timer");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

private static class ImagePanel extends JPanel {

URL[] urls;
BufferedImage[] images;
Random rand = new Random();

public ImagePanel() {
urls = new URL[5];
try {
urls[0] = new URL("http://www.atomicframework.com/assetsY/img/stackoverflow_chicklet.png");
urls[1] = new URL("http://www.iconsdb.com/icons/download/orange/stackoverflow-256.png");
urls[2] = new URL("http://img.1mobile.com/market/screenshot/50/com.dd.stackoverflow/0.png");
urls[3] = new URL("http://www.iconsdb.com/icons/download/orange/stackoverflow-4-512.png");
urls[4] = new URL("http://www.iconsdb.com/icons/preview/light-gray/stackoverflow-xxl.png");

images = new BufferedImage[5];
images[0] = ImageIO.read(urls[0]);
images[1] = ImageIO.read(urls[1]);
images[2] = ImageIO.read(urls[2]);
images[3] = ImageIO.read(urls[3]);
images[4] = ImageIO.read(urls[4]);

} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
setBackground(Color.BLACK);

Timer timer = new Timer(500, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}

private int random() {
int index = rand.nextInt(5);
return index;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage img = images[random()];
g.drawImage(img, 0, 0, 400, 400, 0, 0,
img.getWidth(), img.getHeight(), this);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}

Notice the Timer code. This is all I did

Timer timer = new Timer(500, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();

And for the .grawImage I use a random index from the array of BufferedImages

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage img = images[random()];
g.drawImage(img, 0, 0, 400, 400, 0, 0,
img.getWidth(), img.getHeight(), this);
}

UPDATE Example. I shut down my IDE for the night. Too lazy to open so I'm just going to come up with this as I go. If you still don't it, I'll add a real example tomorrow when I get up.

Basically you want to have global variable for the x and y locations of the mouse image

int x = 0;
int y = 0;

When you draw the image, you want to use these locations

g.drawImage(img, x, y, whatEverWidth, whatEverHeight, this);

In the timer, you can modify the x and y randomly before you paint. Let use some logic.

Let say your scree width is 500 and screen height is 500 and mouse image width is 100 and mouse image height is 100

  • So the max x location will be 400 = screen width - mouse image width
  • And max y location will be 400 = screen height - mouse image height

So now we have our ranges. We know min x location is 0 and min y location is 0. So we want a random number from 0 to 400 for each x and y. So in the timer you can do

Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
x = rand.nextInt(400) + 1;
y = rand.nextInt(400) + 1;
repaint();
}
});

This will repaint your mouse image at a random location every time repaint is called.


UPDATE 2

I don't know what else is there to explain. I did just those things I pointed out(with my original code), just added an x and y and used them to draw the image, and got a random location in the timer. It's works perfectly fine for me. I don't know what you're doing wrong.

Sample Image

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestImageRotate {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
JFrame frame = new JFrame("Image Timer");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

private static class ImagePanel extends JPanel {

URL[] urls;
BufferedImage[] images;
Random rand = new Random();
private int x = 0;
private int y = 0;

public ImagePanel() {
urls = new URL[5];
try {
urls[0] = new URL("http://www.atomicframework.com/assetsY/img/stackoverflow_chicklet.png");
urls[1] = new URL("http://www.iconsdb.com/icons/download/orange/stackoverflow-256.png");
urls[2] = new URL("http://img.1mobile.com/market/screenshot/50/com.dd.stackoverflow/0.png");
urls[3] = new URL("http://www.iconsdb.com/icons/download/orange/stackoverflow-4-512.png");
urls[4] = new URL("http://www.iconsdb.com/icons/preview/light-gray/stackoverflow-xxl.png");

images = new BufferedImage[5];
images[0] = ImageIO.read(urls[0]);
images[1] = ImageIO.read(urls[1]);
images[2] = ImageIO.read(urls[2]);
images[3] = ImageIO.read(urls[3]);
images[4] = ImageIO.read(urls[4]);

} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
setBackground(Color.BLACK);

Timer timer = new Timer(500, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
x = rand.nextInt(325);
y = rand.nextInt(325);
repaint();
}
});
timer.start();
}

private int random() {
int index = rand.nextInt(5);
return index;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage img = images[random()];
g.drawImage(img, x, y, 75, 75, this);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}

Make image disappear after X seconds (processing)

You can use the millis() function or the frameCount variable to check how much time has gone by, then do something after X seconds or after X frames.

You're already doing some of the work with the showimagedone variable, but you need to use that variable to conditionally draw your image.

I recommend starting with a simpler example and getting that working. Here's one example:

int clickedFrame;
boolean on = false;
int duration = 60;

void draw(){

if(on){
background(255);
if(frameCount > clickedFrame + duration){
on = false;
}
}
else{
background(0);
}
}

void mousePressed(){
clickedFrame = frameCount;
on = true;
}

This code show a white background for one second whenever the user clicks the mouse. You need to do something similar with your images.

Related posts:

  • How to make a delay in processing project?
  • How can I draw only every x frames?
  • Removing element from ArrayList every 500 frames
  • Timing based events in Processing
  • How to add +1 to variable every 10 seconds in Processing?
  • How to create something happen when time = x
  • making a “poke back” program in processing
  • Processing: How do i create an object every “x” time
  • Timer using frameRate and frame counter reliable?
  • Adding delay in Processing

Please also consult the Processing reference for more information.

If you still can't get it working, please post a MCVE (not your full project!) in a new question and we'll go from there. Good luck.

How to display a random image for x second once the activity is first brought up?

Ok, so you want to show an image for 5 seconds and you don't want to show the image more often than once a day? This implies that you need to keep track of when you showed the image last, SharedPreferences works well for this. I suggest that you use a custom AlertDialog to show the image. It will look nice and it will dim out the activity in the background. And I'd recommend the use of a Timer and a TimerTask to dismiss the dialog after a certain period of time. Here's an example:

 /**
* imageIds is an array of drawable resource id to chose from
* Put the images you like to display in res/drawable-nodpi (if you
* prefer to provide images for several dpi_bracket you put them in
* res/drawable-mpdi, drawable-hdpi etc).
* Add each of their resource ids to the array. In the example
* below I assume there's four images named myimage1.png (or jpg),
* myimage2, myimage3 and myimage4.
*/
@Overrride
public void onCreate(Bundle savedInstanceState) {
final int[] imageIds = { R.drawable.myimage1, R.drawable.myimage2, R.drawable.myimage3, R.drawable.myimage4 };
final int id = new Random().nextInt(imageIds.length - 1);
showImageDialog(id, 24 * 60 * 60 * 1000, 5000);
}

/**
* Show an image in a dialog for a certain amount of time before automatically dismissing it
* The image will be shown no more frequently than a specified interval
* @param drawableId A resource id for a drawable to show
* @param minTime Minimum time in millis that has to pass since the last time an aimage was shown
* @param delayBeforeDismiss Time in millis before dismissing the dialog
*
*/
private void showImageDialog(int drawableId, long minTime, long delayBeforeDismiss) {
final SharedPreferences prefs = getPreferences(MODE_PRIVATE);
// make sure we don't show image too often
if((System.currentTimeMillis() - minTime) < prefs.getLong("TIMESTAMP", 0)) {
return;
}

// update timestamp
prefs.edit().putLong("TIMESTAMP", System.currentTimeMillis()).commit();

// create a custom alert dialog with an imageview as it's only content
ImageView iv = new ImageView(this);
iv.setBackgroundDrawable(getResources().getDrawable(drawableId));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(iv);
final AlertDialog dialog = builder.create();
dialog.show();

// dismiss it after 5 seconds
new Timer().schedule(new TimerTask() {
@Override
public void run() {
dialog.dismiss();
}
}, delayBeforeDismiss);
}

How to change an image every 5 seconds for example?

you should run 'change' function outside of the func and pass the function name to the setInterval func as below

let images = ['photoFromInternet', 'photoFromInternet2', 'photoFromInternet3'];

let index = 0;
const imgElement = document.querySelector('#mainPhoto');

function change() {
imgElement.src = images[index];
index > 1 ? index = 0 : index++;
}

window.onload = function () {
setInterval(change, 5000);
};

How to use a random array number and a timer in java?

Assuming your array of numbers looks like this, initialized somewhere in your class:

int[] numbers = new int[]{ 123, 321, 456, 765, 923, 931 };

You can create a method looking like this:

private int getRandomNumberFromArray(){
int min = 0;
int max = numbers.length;

return numbers[min + (int)(Math.random() * ((max - min) + 1))];
}

Then you could call that method like this:

int randomNumberFromArray = getRandomNumberFromArray();

Look into this thread for a detailed explanation of Java's Random implementation.

As for your other problems, I'm not quite sure what you are trying to accomplish. Please provide some more details.


Update

With your OP updated, I think I have a better idea of what you're trying to do. Allow me to revise.

First, for getting images displayed with Slick2D, here is a good, short video tutorial. I recommend you check his series on the subject, as they are very clear and concise.

As for your timer, I found this piece of code here.

int time;

public void update(GameContainer container, int delta) {
time += delta;
}

public void render(GameContainer container, Graphics g) {
g.drawString("Time : " + time/1000, 100, 100);
}

This will draw a simply timer that on the screen at x=100, y=100 that updates itself. This is something you could use for test purposes. As for your random interval, you can expand on the above code like this.

int time;
int deadline; // initialize this somewhere in the start of your game

public void update(GameContainer container, int delta) {
time += delta;
}

public void render(GameContainer container, Graphics g) {
g.drawString("Time : " + time/1000, 100, 100);

// if the current time has passed the deadline, do something
if(time > deadline){
int min = 2;
int max = 3;
deadline = time + ((min + (int)(Math.random() * ((max - min) + 1))) * 1000); // reset the interval timer

// draw the image
int x = 100;
int y = getRandomNumberFromArray(); // this is the method I provided in my first part of the answer
Image img = new Image("path/file.png");
g.drawImage(img, x, y) // image file, x, y
}
}

This piece of code creates a deadline that functions as a random interval timer. The deadline is a summation of the current time, to which a number between 2 and 3 will be added (multiplied with 1000, because time is kept in milliseconds). When the current time surpasses this deadline, a random image will be created.

As for displaying multiple images, I would refer to the previously linked tutorial. I think this could be accomplished by keeping track of the images in an ArrayList. Then rendering all of those images in the render() method. But I'm not quite sure since I only know a few basics of Slick2D.

I haven't tested any of this, but I hope to have pointed you into the right direction.

Update 2

As for the recommendation in the comment, this would be a way of implementing that.

ArrayList<DrawnImage> images; // make sure you initialize this at the beginning as: images = new ArrayList<Image>();
int time;
int deadline; // initialize this somewhere in the start of your game

public void update(GameContainer container, int delta) {
time += delta;
}

public void render(GameContainer container, Graphics g) {
g.drawString("Time : " + time/1000, 100, 100);

// if the current time has passed the deadline, do something
if(time > deadline){
int min = 2;
int max = 3;
deadline = time + ((min + (int)(Math.random() * ((max - min) + 1))) * 1000); // reset the interval timer

// draw the image
int x = 100;
int y = getRandomNumberFromArray(); // this is the method I provided in my first part of the answer
images.add(new DrawnImage(new Image("path/file.png"), x, y));

for(DrawnImage di : images){
g.drawImage(di.image, di.x, di.y); // image file, x, y
}
}
}

DrawnImage class

public class DrawnImage {
public Image image;
public float x;
public float y;

public DrawnImage(Image image, float x, float y){
this.image = image;
this.x = x;
this.y = y;
}
}


Related Topics



Leave a reply



Submit