我使用了一个引用同一数组中先前元素的数组来确定下一个值是什么。这样我就可以在绘制多边形时获得位置的相对值。没有报告语法错误,但我在示例中使用的三角形要么不可见,要么不存在。
对于这个例子,我想在窗口的上半部分随机散布小的黑色三角形,而不考虑窗口的边缘和其他三角形。以下是包含我想要实现的示例的代码,但没有使用自引用数组(我在 BlueJ 中编写了此代码,并且从未在 BlueJ 之外编写过任何内容。我不知道如何编写连续的代码所以请耐心等待。我写了两个类中的每一个在每个 // 之后开始的位置:
//第一类
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);
}
}
//下一节课
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);
//The following is the part of the code that doesn't work.
g.setColor(Color.BLACK);
int x=0;//this x is used for the following while loop
int[] xC = new int[3];//these are the x coordinates of the random triangles
int[] yC = new int[3];//these are the y coordinates of the random triangles
while(x<14){//this while loop is used to make many triangles
xC[0]= (int)Math.random()*400;
xC[1]= xC[0]+(int)Math.random()*20;
xC[2]= xC[1]+(int)Math.random()*4;
yC[0]= (int)Math.random()*200;
yC[1]= yC[0]-(int)Math.random()*10;
yC[2]= yC[0]-(int)Math.random()*3;
g.fillPolygon(xC,yC,3);//I changed this to fillPolygon
x++;//this is so the loop will eventually end
}
//the following is the manual part that does work.
int[] xCe = new int[3];//this is the array of x coordinates for the triangle
xCe[0]= 200;
xCe[1]= 210;
xCe[2]= 213;
int[] yCe = new int[3];//this is the array of y coordinates for the triangle
yCe[0]= 300;
yCe[1]= 295;
yCe[2]= 299;
g.fillPolygon(xCe,yCe,3);//this polygon appears properly
//everything after this is just to help explain after compiling
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);
}
}
是什么导致它们看不见?我希望它们是可见的。我不知道我做错了什么。它是自引用数组吗?fillPolygon() 不允许这样做吗?