2016-10-15 4 views
0

자바에서 매우 간단한 프로젝트를 작성하려고합니다. 주 클래스가 2 클래스의 메서드를 실행하여 새 JFrame 개체를 만드는 2 개의 클래스를 만들려고합니다. 그런 다음 주 클래스는 클래스 2의 메서드를 호출하여 2 개의 변수 값을 설정합니다. 그런 다음, 문자열은 set x 및 y 값으로 JFrame 패널에 인쇄되어야합니다. 그러나 xPos와 yPos가 변경되지 않은 것과 같습니다. 문자열은 0,0에 인쇄됩니다. 자바에서 다른 클래스의 변수에 액세스

코드입니다 :

import java.awt.*; 
import javax.swing.*; 

public class Test { 
     public static void main(String[] args){ 
       Class2 obj = new Class2(); 
       obj.createJFrame(); 
       obj.setVal(100, 200); 
     } 
} 

class Class2 extends JPanel{ 
     private int xPos, yPos; 
     public void createJFrame(){ 
       JFrame window = new JFrame(); 
       Class2 obj2 = new Class2(); 
       window.setVisible(true); 
       window.setSize(300, 300); 
       window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       Container c = window.getContentPane(); 
       c.add(obj2); 
     } 
     public void setVal(int x, int y){ 
       xPos = x; 
       yPos = y; 
       repaint(); 
     } 
     public void paintComponent(Graphics g){ 
       super.paintComponent(g); 
       g.drawString("This string should be at 100, 200", xPos, yPos); 
     } 
} 

보조 노트로서, 나는 나의 제목이 정확하다고 생각하지 않는다, 그래서 누군가가 제목을 편집하여 나를 도울 수 있다면 그것은 좋은 것입니다. 제목이 질문과 일치하지 않는 경우 유감이지만 자바를 처음 사용합니다. 또한이 프로그램은 좀 더 복잡한 프로그램을 모델링하기 때문에이 방법이 간접적으로 비효율적으로 보이면 더 복잡한 프로그램이 이와 같은 구조를 사용하기 때문입니다. 미리 감사드립니다.

답변

2
class Class2 extends JPanel{ 
     private int xPos, yPos; 
     public void createJFrame(){ 
       JFrame window = new JFrame(); 
       // Class2 obj2 = new Class2(); 
       window.setVisible(true); 
       window.setSize(300, 300); 
       window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       Container c = window.getContentPane(); 
       c.add(this); // now the setValue will update the object 
     } 
... 

JFrame에 추가 된 개체를 업데이트하지 않았습니다. 제쳐두고 정적 메서드 나 다른 클래스에서 JFrame을 만들고 Class2를 인수로 사용합니다. 예 :

class Class2 extends JPanel{ 
    private int xPos, yPos; 
    public static void createJFrame(Class2 obj){ 
      JFrame window = new JFrame(); 
      window.setVisible(true); 
      window.setSize(300, 300); 
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      Container c = window.getContentPane(); 
      c.add(obj); 
    } 
    public void setVal(int x, int y){ 
      xPos = x; 
      yPos = y; 
      repaint(); 
    } 
    public void paintComponent(Graphics g){ 
      super.paintComponent(g); 
      g.drawString("This string should be at 100, 200", xPos, yPos); 
    } 
} 

public class Test { 
    public static void main(String[] args){ 
     Class2 obj = new Class2(); 
     obj.setVal(100, 200); 
     Class2.createJFrame(obj); 
    } 
} 
+0

감사합니다. 나는 객체를 매개 변수로 사용하는 것에 대해 배웠지 만, 첫 번째는 여전히 잘 동작합니다. 두 번째 방법에 대해 알게되면 이해가 될 것이며 더 나아질 것입니다. 현재로서는 첫 번째 방법이 잘 작동합니다. – SAT

+0

[* 초기 스레드 *] (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)도 참조하십시오. – trashgod

관련 문제