Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java: How to make an ImageIcon appear/reappear randomly for random duration?  RSS feed

Amber Alegria
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all. I am needing an explanation on how to make an ImageIcon object appear/reappear randomly for random duration.
I have tried to instantiate a Random object and use that for setting duration when instantiating a Timer object, but it
did not work. I think I can only use a constant for a Timer. Also, in my actionPerformed method, I think I need to
write logic to somehow assign x and y random integers within a range to make the image appear/reappear randomly, but I
am not sure.

Again, I am only looking for explanations to my problem, I am not expecting a handout or even code examples (though that would help). This is a homework assignment, but I am more interested in learning how to solve the problem, not merely finishing the assignment. (It is already past due, so I won't get any credit anyways). My intention is to learn Java, not get the grades. I hope I have described my problem accurately. If there is anything that I did not explain clearly, please let me know. Thank you for your time.

Here is my code, it does compile, but the movement of the image is smooth and constant and not random at all. I need it to appear/reappear randomly.

[Thumbnail for UMadBro.gif]
Piet Souris
Posts: 1979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Amber,

the easiest way to get what you want is to incorporate the following statement in your actionPerformed-method:

and you can also set some random displacements for your x and y here as well.

Winston Gutkowski
Posts: 10573
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amber Alegria wrote:Here is my code...


First: Welcome to JavaRanch.

Second: Please DontWriteLongLines. It makes your thread very hard to read, and it's actually bad coding practice. The rule here is:
80 characters max.
(the SSCCE page actually recommends 62)
And that includes string literals AND comments AND long method calls.

I'd break yours up myself, but you have tons of them. However, you can edit your post with the 'Edit' button.
If you do, use the 'Preview' button before you re-save.


  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!