所以我基本上只是试图在循环中绘制一大堆随机三角形到屏幕,同时改变颜色似乎不是很困难但我找不到我的问题所在......它不会循环它只显示一个图像这里有我的
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
public class ManyTriangles extends Canvas {
public void paint(Graphics g) {
Random r = new Random();
int x1 = r.nextInt(350);
int x2 = r.nextInt(400);
int x3 = r.nextInt(300);
int y1 = r.nextInt(800);
int y2 = r.nextInt(200);
int y3 = r.nextInt(600);
int[] xpts = { x1, x2, x3 };
int[] ypts = { y1, y2, y3 };
int randomColor = r.nextInt(3);
for (int x = 0; x <= 500; x++) {
if (randomColor == 3) {
g.setColor(Color.green);
} else if (randomColor == 2) {
g.setColor(Color.red);
} else if (randomColor == 1) {
g.setColor(Color.blue);
}
g.fillPolygon(xpts, ypts, 3);
}
}
public static void main(String[] args) {
ManyTriangles canvas = new ManyTriangles();
JFrame frame = new JFrame("Lots of Triangle's");
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(canvas);
frame.setVisible(true);
}
}
答案 0 :(得分:3)
xpts
和yppts
永远不会在循环中发生变化,因此您会以不同的颜色一遍又一遍地绘制相同的内容super.paint
Canvas
上混合了重量级和轻量级的组件(JFrame
),这不是一个好主意...... xpts
和yppts
的创建移至loop
super.paint
JPanel
代替Canvas
并覆盖它的paintComponent
方法,确保在进行任何自定义绘画之前调用super.paintComponent
... 有关详细信息,请参阅Painting in AWT and Swing,Performing Custom Painting
paint
时都会重新生成输出,所以输出可能会随机变化(因为重绘管理器会调度新的重绘请求)。如果您不想这样,请在构造函数或其他方法中生成形状,将它们添加到某种List
或数组中,并在paintComponent
方法中对其进行迭代...