0

The thing is that I'm a beginner on this of programming and I'm trying to make a program that simulates a rainfall. My problem is when I want to make an array of various raindrops fall they didn't.

Previously I've made a class for a drop, and I made the array in other class. So when I execute the program, this paint all the array of drops in different x positions but those didn't move down.

This is the code of Drop class:

public class Drop
{
    private Random random = new Random();
    private int x = random.nextInt(600);
    private int y;
    private int yspeed;

    public Drop()
    {
        random = new Random();
    }

    public void fall()
    {
        y = y + yspeed;
    }

    public void draw(Graphics g)
    {
        g.setColor(Color.BLUE);
        g.drawLine(x, y, x, y + 15);
    }
}

And this is the class where it's painted:

public class Panel extends JPanel
{
    private Drop[] drops = new Drop[100];
    private Drop d = new Drop();

    private static final long serialVersionUID = 1L;


    public Panel()
    {
        setBackground(Color.CYAN);
        for (int i = 0; i < drops.length; i++)
        {
            drops[i] = new Drop();
        }
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        for (int i = 0; i < drops.length; i++)
        {
            d.fall();
            drops[i].draw(g);
        }
    }
}

I'm a beginner on this and I'll appreciate any help you give me. Thanks.

George Z.
  • 6,643
  • 4
  • 27
  • 47
BETULIOsMay
  • 1
  • 1
  • 5
  • 1
    You're not setting `yspeed` to anything anywhere, and I believe the default for `int` in Java is `0`. – jmoerdyk Aug 15 '19 at 22:03
  • You'll also need a "animation loop" to update the state of the drop on a periodical period, in Swing, the best solution is to use a Swing `Timer` – MadProgrammer Aug 15 '19 at 22:05
  • [For example](https://stackoverflow.com/questions/45139253/how-to-make-painted-objects-on-applet-canvas-blink/45141219#45141219) and [example](https://stackoverflow.com/questions/48977423/programming-rain-in-java/48978663#48978663) – MadProgrammer Aug 15 '19 at 22:06
  • Oh you're right jmoerdyk, i have to set the yspeed haha. Thanks for answer :) – BETULIOsMay Aug 15 '19 at 23:23
  • And you MadProgrammer, yes I have much to learn about animation and stuff. I'll keep your advice. Thanks for answer as well :) – BETULIOsMay Aug 15 '19 at 23:26
  • See those 2 examples of "rain" like animation : [1](https://stackoverflow.com/a/54158677/3992939) and [2](https://stackoverflow.com/a/43706965/3992939) (btw vertical gravitational fall should not be with constant speed but accelerating) – c0der Aug 16 '19 at 08:06

0 Answers0