我正在尝试构建一个程序,其中随机创建至少 10 个形状并随机分配位置。到目前为止,我有这个:
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);
}
}
和
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());
}
}
和
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 [行:14] 错误:找不到符号符号:方法 Graphics() 位置:RandomShapeGenerator 类型的变量 r
- 此外,关于我的第一个问题的后续问题:我如何才能用纯色填充椭圆形和矩形等?