Java AWT Graphics draw lines with random location

Description

Java AWT Graphics draw lines with random location

import java.awt.Graphics;
import java.awt.Insets;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Demo extends JPanel {

   public void paint(Graphics g) {
      super.paintComponent(g);

      int x, y, x2, y2;

      // Get the height and width of the component.
      int height = getHeight();
      int width = getWidth();
      Random rand = new Random();
      // Get the insets.
      Insets ins = getInsets();// w w w  . j ava  2 s .c o  m

      // Draw ten lines whose end points are randomly generated.
      for (int i = 0; i < 10; i++) {
         x = rand.nextInt(width - ins.left);
         y = rand.nextInt(height - ins.bottom);
         x2 = rand.nextInt(width - ins.left);
         y2 = rand.nextInt(height - ins.bottom);

         // Draw the line.
         g.drawLine(x, y, x2, y2);
      }
   }

}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related