我必须制作一个绘制Sierpinski Triangle的程序。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SierpinskiPanel extends JPanel{
private SierpinskiFrame frame;
public SierpinskiPanel(SierpinskiFrame f){
frame = f;
}
也就是说,我无法在递归方法中访问变量g。我将如何使变量可访问或将方法放入方法paintComponent中?
public void drawSierp(int width, int height, int x, int y){
int leftCornY = height;
int rightCornY = height;
int rightCornX = width;
if(width == 1 && height == 1){
g.drawRect(x, y, 1, 1);
}
else{
drawSierp(width/4, height/4, x, leftCornY);
drawSierp(width/4, height/4, rightCornX, rightCornY);
drawSierp(width/4, height/4, width/2, height/2);
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int w = frame.getWidth();
int h = frame.getHeight();
int xCoord = frame.getX();
int yCoord = frame.getY();
drawSierp(w, h, xCoord, yCoord);
}
}
答案 0 :(得分:0)
将方法更改为
public void drawSierp(Graphics g, int width, int height, int x, int y)
,最初从paintComponent
调用为
drawSierp(g, w, h, xCoord, yCoord);
当然,您也需要从else
块调用中传递它。
答案 1 :(得分:0)
您尚未将对象g
传递给drawSierp()
。因此该方法应该获取传入的参数。
public void drawSierp(int width, int height, int x, int y, Graphics g){
int leftCornY = height;
int rightCornY = height;
int rightCornX = width;
if(width == 1 && height == 1){
g.drawRect(x, y, 1, 1);
}
else{
drawSierp(width/4, height/4, x, leftCornY, g); // Pass the object g'
drawSierp(width/4, height/4, rightCornX, rightCornY, g); // Pass the object 'g'
drawSierp(width/4, height/4, width/2, height/2 , g); // Pass the object 'g'
}
}
调用函数时,应提供所有参数。