2012-07-05 2 views
1

3 가지 클래스가있는 응용 프로그램을 만들려고합니다. Controller (Main Class), SerialHandler 및 MainWindow는 NetBeans Gui Builder로 생성 된 JFrame Form입니다.Netbeans GUI 및 비 정적 메서드

public class Controller { 
    SerialHandler serialHandler; 
    MainWindow mainWindow; 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // TODO code application logic here 
     Controller controller = new Controller(); 
     controller.initializeSystem(controller); 
    } 
    public void initializeSystem(Controller _controller){ 
     mainWindow = new MainWindow(_controller); 
     mainWindow.setVisible(true); 
    } 
    public void anotherMethod(){ 
     mainWindow.setMyLabelText("Hello"); 
    } 
} 

그래서 문제는 내가 그렇게 작은 동전과 SerialHandler 클래스 이벤트가 anotherMethod()를 호출하는 경우 setMyLabelText 방법이 작동하지 않는다는 것입니다하지만 난)합니다 (initializeSystem에서 호출하는 경우; 그것은 작동합니다.

메인에 메인 윈도우를 선언하면 mainWindow 인스턴스가 anotherMethod()에서 보이지 않습니다.

주 외부에서 mainWindow 객체를 선언하고 주 컨텍스트에서 해당 메서드를 사용하려고하면 mainWindow 객체가 정적이 아닌 컨텍스트 외부에서 선언 되었기 때문에 그렇게 할 수 없습니다.

누구나 나를 도와 주거나 적어도 올바른 방향으로 나를 가리킬 수 있습니까?

감사합니다.

public static void main(String[] args) { 
     // TODO code application logic here 
     Controller controller = new Controller(); 
     controller.initializeSystem(controller); 
    } 
    public void initializeSystem(){ 
     mainWindow = new MainWindow(_controller); 
     mainWindow.setVisible(true); 
    } 

당신은 방금 initializeSystem 내부 this를 사용할 수 있기 때문에 불필요하다 그 initializeSystem에 인수로 전달하는 컨트롤러를 만드는 :

+0

참조가 필요한 개체로 전달해야합니다. 이것은 생성자 매개 변수 또는'setXXX (...)'setter 메소드를 사용하여 수행 할 수 있습니다. –

+1

코드가 public으로 컴파일되지 않습니다 anotherMethod() {invalid java syntax – ControlAltDel

+0

문제는 내가 만든 클래스에 mainWindow 객체를 전달하는 것입니다. 내 메서드는 컨트롤러 클래스에 있지만이 클래스 안에 내 mainWindow를 만드는 ... 그래서 할 수 있습니까? – Twistx77

답변

2

코드와 설계 불일치가있다.

대신이 작업을 수행해야합니다

public static void main(String[] args) { 
     // TODO code application logic here 
     Controller controller = new Controller(); 
     controller.initializeSystem(); 
    } 
    public void initializeSystem(Controller _controller){ 
     mainWindow = new MainWindow(this); 
     mainWindow.setVisible(true); 
    } 

두 번째 모순은 당신의 UI 및 업데이트 물건에 액세스하는 방법 anotherMethod입니다. 대신 컨트롤러에 맡겨야합니다. 이런 식으로 뭔가 : 그것은가 필요로 할 때

public class Controller { 
    //... 

    public void updateUIText(String text){ 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
       mainWindow.setMyLabelText("Hello"); 
       } 
      }); 
    } 
} 

이제 SerialHandler는 컨트롤러를 통해 UI를 업데이트 할 수 있습니다. 당신이해야 할 무엇을 모든이가 Controller가 제대로 심지어 멀티 스레드 시나리오에서 UI를 업데이트 할 것입니다 보장합니다 나는 UI를 업데이트 할 SwingUtilities.invokeLater을 사용 SerialHandler

편집 주에 Controller 참조 전달되는 I 귀하의 사건을 가정하십시오.

+0

그것이 바로 제가 전화하는 것입니다. 나는 run()에 익숙하지 않지만 그것을 시도 할 것이다 :). 감사. 이것에 대한 다른 아이디어는 감사하겠습니다. – Twistx77

+0

@ Twistx77 도움이 됨 :)'run()'메소드는 UI를 EDT라고하는 UI 스레드에서 업데이트합니다. – GETah

관련 문제