Meaningless Drivel is fun!
The moose likes Swing / AWT / SWT and the fly likes Help with snow Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Help with snow" Watch "Help with snow" New topic

Help with snow

mark geroso

Joined: Oct 12, 2006
Posts: 24
I'm supposed to make a frame with a snowman and falling snow. I've finished the snowman, but I've suddenly run into a mind block.
I can't, for the life of me, figure out how to make falling snow. Algorithm suggestions would be greatly appreciated, as would actual code snippets.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
I just slapped something together and it seemed to work OK
add to a frame, a panel with a background image of a snowman.
set the frame's size(500,500) and setResizable(false) - not the best, but you can hard-code some of the values this way.
add to the panel another panel (transparent) - this handles the snow

classes for the snow
int x, y (for coords)
set y = 10, x = a random int(500)
has an array of SnowFlakes
array.length is a random number say, 5 to 10

in the transparent panel, have an arraylist for snowLayers
start a timer, to do:
1) add a snowLayer
2) repaint
3) check arraylist.size() == 10, remove(0), and add a new snowLayer

in the transparent panel's paintComponent()
1) super.paintComponent(g);
2) setColor to white
3) iterate the snowLayer arraylist, with inner iteration of each snowlayer's
snowFlakes array - to get to each snowFlake's x and y, then g.fillOval(x,y,10,10)
also inside the inner iteration add 50 to each snowFlake's y (this will have
the effect of the snowlayer 'falling'

put it all together, and, well, it's not brilliant, but it works.
(from there you can tweak a few things)
mark geroso

Joined: Oct 12, 2006
Posts: 24
I have several snowflake images I load and use. The problem with my code is that the panel with the snowman gets covered. And the snowflake images leave a trail. I can't upload the snowflake images, but I'm sure that just by looking at the code you gurus can point out my mistake. *crosses fingers*

I did rewrite it without all the panels, just drawing on the frame itself, and it generally worked, but the snowman flickered a lot, because it kept getting repainted and that was what I was trying to avoid.
Sorry for the long post and I hope you can help. Thanks. If you need me to post the code without the panels, lemme know.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
don't have time to go through it all at present, but this is what I'd slapped
together - not brilliant, but the concept seems to work OK (might be something
in it for you)

needs Snowman.gif

I agree. Here's the link:
subject: Help with snow
It's not a secret anymore!