Using self-referential arrays, polygons are invisible
I used an array that refers to previous elements in the same array to
determine what the next value will be. This is so that I can get relative
values for position when drawing polygons. There are no reported syntax
errors, but the triangles I use here in the example are either invisible
or don't exist.
For this example, I would like to make small black triangles randomly
scattered in the top half of the window without regard for the window's
edges and the other triangles. The following is the code which includes an
example of what I'm trying to achieve, but without using a
self-referential array (I wrote this in BlueJ and have never written
anything outside of BlueJ. I don't know how to write continuous code so
please bear with me. I wrote where each of the two classes begin after
each // :
//first class
import javax.swing.*;
public class patterns {
public static void main(String[] args) {
JFrame f = new JFrame("Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
example p = new example();
f.add(p);
f.setSize(400,400);
f.setVisible(true);
}
}
//next class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
public class example extends JPanel{
public void paintComponent (Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
int[] xC = new int[3];
xC[0]= (int)Math.random()*400;
xC[1]= xC[0]+(int)Math.random()*20;
xC[2]= xC[1]+(int)Math.random()*4;
int[] yC = new int[3];
yC[0]= (int)Math.random()*200;
yC[1]= yC[0]-(int)Math.random()*10;
yC[2]= yC[0]-(int)Math.random()*3;
g.setColor(Color.BLACK);
int x=0;
while(x<14){
g.drawPolygon(xC,yC,3);
x++;
}
int[] xCe = new int[3];
xCe[0]= 200;
xCe[1]= 210;
xCe[2]= 213;
int[] yCe = new int[3];
yCe[0]= 300;
yCe[1]= 295;
yCe[2]= 299;
g.fillPolygon(xCe,yCe,3);
g.drawString("There should be a whole bunch of little triangles
that look",20,320);
g.drawString("sort of like this one, but on the top half of this
window.", 40,340);
g.drawLine(170,270,200,290);
g.drawLine(194,289,200,290);
g.drawLine(197,285,200,290);
g.drawString("this one",140,260);
}
No comments:
Post a Comment