我试图在逐个像素的基础上绘制谢尔宾斯基三角形,只要窗口大小发生变化,该三角形就会自行调整大小。我相信我已经完成了大部分项目,但我不太知道如何从 PaintComponent 方法外部的单独递归函数中绘制矩形。
public class SierpTriangle extends JPanel
{
public final int x = this.getWidth();
public final int y = this.getHeight();
public final int side = getsize();
public int getsize()
{
int width = this.getWidth();
int height = this.getHeight();
if (width <= height)
{
return width;
}
else
{
return height;
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawSierpTriangle(this.x, this.y, this.side);
g.drawRect(x,y,1,1);
}
public void drawSierpTriangle(int x, int y, int size)
{
if (size == 1)
{
//Draw rectangle? This is where I need help
g.drawRect(x,y,1,1); //this does not work, passing Graphics g into the method also does not work
}
else
{
drawSierpTriangle(x/2, y, size/2);
drawSierpTriangle(x,y/2,size/2);
drawSierpTriangle(x/2,y/2,size/2);
}
}
public static void main(String[] args)
{
new SierpFrame();
}
}
最佳答案
将Graphics
的引用从paintComponent
传递到drawSierpTriangle
public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawSierpTriangle(g, this.x, this.y, this.side);
g.drawRect(x,y,1,1);
}
public void drawSierpTriangle(Graphics g, int x, int y, int size)
{
if (size == 1)
{
//Draw rectangle? This is where I need help
g.drawRect(x,y,1,1); //this does not work, passing Graphics g into the method also does not work
}
else
{
drawSierpTriangle(g, x/2, y, size/2);
drawSierpTriangle(g, x,y/2,size/2);
drawSierpTriangle(g, x/2,y/2,size/2);
}
}
This results in: Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at the first recursive call of the method. Any input?
public final int side = getsize();
将使side
永远0
。
用更像...的东西替换它
public int getSide() {
int width = this.getWidth();
int height = this.getHeight();
if (width <= height) {
return width;
} else {
return height;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int side = getSide();
if (side == 0) return;
drawSierpTriangle(g, this.x, this.y, side);
g.drawRect(x, y, 1, 1);
}
每次绘制组件时,都会评估side
。如果 side 为 0
您也会遇到与 x
和 y
相同的问题,因为状态永远不会改变
关于java - 从单独的方法使用 java awt drawRect 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859591/