Java 我能';t使用单独的方法访问我的变量
我要做一个程序画一个Sierpinski三角形Java 我能';t使用单独的方法访问我的变量,java,Java,我要做一个程序画一个Sierpinski三角形 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SierpinskiPanel extends JPanel{ private SierpinskiFrame frame; public SierpinskiPanel(SierpinskiFrame f){ frame = f; } 也就是说
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。我将如何使变量可访问,或将方法放入方法组件中
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);
}
}
将您的方法更改为
public void drawSierp(Graphics g, int width, int height, int x, int y)
并从paintComponent
开始将其称为
drawSierp(g, w, h, xCoord, yCoord);
当然,您还需要从
else
块调用传递它。将您的方法更改为
public void drawSierp(Graphics g, int width, int height, int x, int y)
并从paintComponent
开始将其称为
drawSierp(g, w, h, xCoord, yCoord);
当然,您还需要从
else
块调用传递它。您还没有将对象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'
}
}
调用函数时,应给出所有参数。您尚未将对象
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'
}
}
调用函数时,应给出所有参数
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'
}
}