lundi 16 mars 2015

How to put different color random dots in a rectangle separated by a diagonal (JAVA)

My problem is that I cant get the diagonal to resize properly. If I run the code the diagonal is on the wrong side and when I expand it vertically it doesn't maintain a perfect diagonal from one corner to another.


Below I have my code for the program and the driver. import javax.swing.JFrame;



public class Points
{

public static void main(String[] args)
{
JFrame frame = new JFrame("Points");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

PointsPanel panel = new PointsPanel();

frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}


Here is the main program



import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import java.awt.Color;
import java.lang.Math.*;

public class PointsPanel extends JPanel
{
private final int MAX_POINTS = 20000;
private final int LENGTH = 1;
private int x,x1,y,y1;
private Random random;
double slope,b,c,g;


public PointsPanel(){
random = new Random();
setBackground(Color.black);
setPreferredSize(new Dimension(300,300));

}


public void paintComponent(Graphics page)
{
super.paintComponent(page);
for(int count = 0; count < MAX_POINTS; count++)
{

x = random.nextInt(getWidth()-1) + 1;

y = random.nextInt(getHeight()-1) + 1;

x1= x + LENGTH;
y1= y + LENGTH;

slope = x1/y1;
c = slope*x;
b = ((-1)*(y))-c;
g = (-1)*y1;

if (b <= g)

page.setColor(Color.red);
else
page.setColor(Color.green);
page.drawLine(x,y,x1,y1);
}
}
}




Aucun commentaire:

Enregistrer un commentaire