Random shape generator in Java
我正在尝试构建一个程序,其中至少有10个形状随机创建并随机放置。 到目前为止我有这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import javax.swing.JFrame; public class RandomShapeViewer { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("RandomShapeViewer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RandomShapesComponent component = new RandomShapesComponent(); frame.add(component); frame.setVisible(true); } } |
和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import javax.swing.JComponent; import java.awt.Graphics; import java.awt.Graphics2D; public class RandomShapesComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; RandomShapeGenerator r = new RandomShapeGenerator(getWidth(), getHeight()); for (int i = 1; i <= 10; i++) g2.draw(r.Graphics()); } } |
和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.util.Random; import java.awt.*; import java.awt.event.*; public class RandomShapeGenerator { int width, height; Random ran = new Random(); public RandomShapeGenerator(int i, int j) { int width = i; int height = j; } public void paintComponent(Graphics g) { switch(ran.nextInt(10)) { default: case 0: g.drawOval(10, 20, 10, 20); case 1: g.drawLine(100, 100, 150, 150); case 2: g.drawRect(30,40,30,40); } } } |
现在我有几个问题:
找到1个错误:
文件:D: Downloads Wallpaper randomShapesComponent.java [line:14]
错误:找不到符号
符号:方法Graphics()
location:RandomShapeGenerator类型的变量r
is it possible to draw multiple lines in one case (and thus creating a triangle)
当然。 只需使用三角形的坐标调用
I also get this error message 1 error found
您没有所有必需的导入,或者源代码中有拼写错误。 你确定
how would i be able to fill in the Oval and Rectangle etc with a solid color.
使用