Printing Random Colored Lines in Java

Problem:

Create a GUI-based java application that prints colored lines randomly.< br />< br />

Output:



Prompt Picture Description

Solution:

//*******************MyLine.java********************/
import java.awt.Color;
import java.awt.Graphics;

public class MyLine {
 
 private int x1,x2,y1,y2;
 private Color myColor;
 
 
 
 public MyLine(int x1, int x2, int y1, int y2, Color myColor) {
  this.x1 = x1;
  this.x2 = x2;
  this.y1 = y1;
  this.y2 = y2;
  this.myColor = myColor;
 }



 public void draw(Graphics g) {
  g.setColor(myColor);
  g.drawLine(x1, y1, x2, y2);
 }
 

}


//********************RandomShapesFrame.java**********/
import javax.swing.JFrame;

public class RandomShapesFrame {

 public static void main(String[] args) {
  
  JFrame frame = new JFrame("Polygons");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  frame.getContentPane().add(new RandomShapesPanel());
  frame.pack();
  frame.setVisible(true);
  
 }

}


//******************RandomShapesPanel.java**********/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JPanel;

public class RandomShapesPanel extends JPanel {
 
 private MyLine[] lines;
 private Random rnd = new Random();
 
 public RandomShapesPanel() {
  
  lines = new MyLine[5 + rnd.nextInt(5)]; //between 5 & 9 lines. 
  
  int x1, x2, y1, y2;
  Color myColor;
  
  for(int count=0; count < lines.length; count++) {
  
   x1 = rnd.nextInt(300);
   x2 = rnd.nextInt(300);
   y1 = rnd.nextInt(300);
   y2 = rnd.nextInt(300);
   
   myColor = new Color(rnd.nextInt(256),rnd.nextInt(256),rnd.nextInt(256));
   
   lines[count] = new MyLine(x1,x2,y1,y2,myColor);
   
  }
  
  setBackground(Color.white);
  setPreferredSize(new Dimension(300,300));
  
 }

 @Override
 protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  for(MyLine line : lines)
   line.draw(g);
 }
 
}


1 comment :

  1. Liposculpture female Korea Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact