Write a program that displays randomly generated triangles in different colors. Each triangle should be filled with a different colors. Use GeneralPath andl method fill of class Graphics2D to draw triangles.( File must be save as: Assignment10iv)
import java.awt.*;//Color;
import java.util.Random;
//import java.awt.Graphics;
//import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import javax.swing.JPanel;
import javax.swing.JFrame;
class RandomTriangles extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d= (Graphics2D) g;
Random random=new Random();
for(int i=0; i<10; i++)
{
GeneralPath triangle=new GeneralPath();
int x=random.nextInt(375);
int y=random.nextInt(375);
triangle.moveTo(x,y);
x=random.nextInt(375);
y=random.nextInt(375);
triangle.lineTo(x,y);
x=random.nextInt(375);
y=random.nextInt(375);
triangle.lineTo(x,y);
triangle.closePath();
g2d.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
g2d.fill(triangle);
}
}
}
public class Assignment10iv
{
public static void main(String args[])
{
JFrame frame=new JFrame("Drawing triangles....");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomTriangles randomTriangles =new RandomTriangles();
frame.add(randomTriangles);
frame.setSize(400,400);
frame.setVisible(true);
}
}
////////////////////////////////////////////
Copy & paste this code in your Textpad & run, then you will get output.......
If you have any problem please comment below.........
Copy & paste this code in your Textpad & run, then you will get output.......
If you have any problem please comment below.........