RANDOM FIGURES MADE EASY 

JAVA

This tutorial will show you how to do a JFrame with random rectangles


INTRODUCTION
Java has the ability to draw text and graphics using GUI. Graphics can only work by importing AWT package allow us to draw primitive geometric types like rectangle line and circle. Other than this it can also display text.  This tutorial will explain various functions of Graphics class used to draw shapes and text.

Simple rectangle example:













The paint method is the most important one, now for the random figures you just do your random function. Now there are two main options, either the figures are placed in random positions or in random shapes


Getting X & Y 
(next int is necessary for not repeating numbers)



  1. import java.awt.Graphics;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class DrawRect extends JFrame {
    static JPanel pnl = new JPanel();

  2.      public class DR(int a, int b, int c){
             Graphics fig= pnl.getGraphics();
  3.         figuras.fillRect(a, b, c, c);
  4. }
  5. public static void main(String[] args) {
  6. Random ran = new Random();
            for (int z= 0; z < 2; z++) {
                int x = ran.nextInt(500);
                int y = ran.nextInt(500);
    int p = ran.nextInt(500);
  7. DR(x,y,p);

  8. }
  9. JFrame frame= new JFrame("JavaDrawing");
  10. frame.setSize(300, 300);
  11. frame.setVisible(true);
  12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  13. frame.setResizable(false);
  14. }
  15. }
For more info chek out this video:


Comentarios