다음 프로그램을 이해할 수있는 한 폴리곤을 만드는데 왜 작동하지 않습니까? 이것은 다른 클래스에서 drawPolygon 함수에 대한 인수를받습니다.
package test1;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Sc extends JPanel {
int[] xpoints=new int[10];
int[] ypoints=new int[10];
int npoints;
public void method(int a[],int b[], int num){
xpoints=a;
ypoints=b;
npoints=num;
}
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
g.drawPolygon(xpoints, ypoints, npoints);
}
public static void main(String[] args) {
MainClass mc = new MainClass();
mc.fun();
JFrame frame = new JFrame();
frame.getContentPane().add(new Sc());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
}
이것은 MainCLass.java입니다.
package test1;
public class MainClass {
int x[] = {25, 145, 25, 145, 25};
int y[] = {25, 25, 145, 145, 25};
int npoints = 5;
public void fun(){
Sc sc = new Sc();
sc.method(x,y,npoints);
}
}
나는이 코드를 보았지만 무엇이 잘못되었는지 모르겠습니다. 나는 Java를 처음 사용합니다. 누군가 나를 도울 수 있습니까? 미리 감사드립니다.
코드가 정말 지저분하고 읽기 쉽지 않지만 문제는 그림을 그리는 대신 다른 Sc 인스턴스를 창에 추가한다는 것입니다.
frame.getContentPane().add(new Sc());
대신 정적 메서드에서 수행 할 수없는 "this"를 추가해야하지만 Sc 인스턴스를 만들고 메서드로 초기화 할 수 있습니다.
public static void main(String[] args) {
Sc sc = new Sc();
MainClass mc = new MainClass();
mc.fun(sc);
sc.initFrame();
}
public void initFrame() {
JFrame frame = new JFrame();
frame.getContentPane().add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
또한 sc를 "fun"메소드의 인수로 가져와야합니다 (그런 다음 sc 객체에서 "method"메소드를 호출합니다 ... 다시 한 번이 작업은 훨씬 덜 혼란스러운 하나의 클래스에서만 수행 할 수 있습니다).
public void fun(Sc sc){
sc.method(x,y,npoints);
}
이것은 여전히 정말 지저분하지만 적어도 지금은 작동합니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다