samedi 11 juin 2016

Randomly falling Rectangles in JAVA

I am trying to make random rectangles fall from random x coordinate at the top of my panel.

I have rectCreate class like ;

import java.awt.Graphics;
import java.awt.Rectangle;

public class rectCreate extends Rectangle{

    static int x;
    static int y;
    static int a;
    static int b;

    public rectCreate(int x, int y, int a, int b) {
        super();
        rectCreate.x = x;
        rectCreate.y = y;
        rectCreate.a = a;
        rectCreate.b = b;
    }

    public void paint(Graphics g){

        g.drawRect(x, y, b, a);
    }

    public void fall(){

        y = y+2;
    }   
}

Panel class is like;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class panel extends JPanel implements ActionListener{

    Random rnd = new Random();
    int x =  rnd.nextInt(800) , y =0, a = 30, b = 30;
    Timer timer = new Timer(10, this);
    int now = (int) System.currentTimeMillis();
    int passedTime = 600;
    int rectCount;
    int rectStock;
    int rectMax;
    int time = 1000;
    rectCreate rect = new rectCreate(x, y, a, b);
    ArrayList<rectCreate> rects = new ArrayList<rectCreate>();



    public panel(){
        super();
        timer.start(); 


    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
                passedTime = (int) (System.currentTimeMillis() - now);
                rect.paint(g);
                repaint();

                for(int i =0; i<= rectStock ;i++){

                    if(passedTime > time){

                    x =  rnd.nextInt(800);
                    rects.add( new rectCreate(x, y, a, b));
                    rects.get(i).paint(g);
                    repaint();
                    now = (int) System.currentTimeMillis();
                    System.out.println(rects.size());
                    repaint();
                    }
         }
    }
    @Override
    public void actionPerformed(ActionEvent e) {    

        rect.fall();
        repaint();

    }

}

And finally main class ;

import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) {


        JFrame frame = new JFrame("Düşen Kafalar");
        panel panel = new panel();
        frame.setBounds(300, 200, 800, 480);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(panel);

    }

}

But Its not working as I want. Rectangle is being created but after its just renewing, not adding a new rectandle. I want rectangels fall like raing.

Thanks in advance for your help...

Aucun commentaire:

Enregistrer un commentaire