2016-07-23 3 views
-8

내가 이해할 수있는 한, 다음 프로그램은 다각형을 만든다. 그러나 왜 작동하지 않는가? 이것은 다른 클래스의 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.Could 누군가에 새로운 오전에 어떤 문제가 있는지 알 수 없습니다. 사전에 감사합니다.

+1

당신의 예상 동작을 설명시겠습니까 당신의 프로그램? – SerCe

+0

두 개의 서로 다른'Sc' 객체가 있습니다. – Stewart

+0

어떤 주요 방법을 실행하고 있으며 왜 작동하지 않는다고 생각하십니까? – user902383

답변

1

코드가 문제가 당신이 창에 사우스 캐롤라이나의 다른 인스턴스를 추가하는 것이 아니라 당신이 드로잉 된 하나 추가하는 것입니다 (읽기 쉽고되지 않음) 정말 지저분하지만 대신

frame.getContentPane().add(new Sc()); 

을 당신은 또한에 인수로 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 개체에서 "메서드"메서드를 호출 ... 다시 th 하나 개의 클래스에서 수행 할 수 있습니다 덜 혼란 많은)이 될 것이다 :

public void fun(Sc sc){ 
    sc.method(x,y,npoints); 
} 

이 여전히 정말 지저분하지만, 적어도 지금 작동을)

관련 문제