2011-01-19 9 views
4

좋아, 어리석은 질문 일지 모르지만 나는 나쁜 습관을 갖기 전에 자바에 익숙하지 않고 자신에게 올바른 방법을 가르치려고한다.자바로 창 닫기 및 닫기

어쨌든 저는 지난 밤에 프레임을 확장하는 사용자 정의 클래스와 캔버스를 확장하는 사용자 정의 클래스로 구성된 프로그램을 작성했습니다. main() 메서드는 캔버스 클래스에 있으며 프레임 클래스의 인스턴스를 만듭니다. 문제는 프로그램이 윈도우 닫기 이벤트를 감지하면 메인 메서드 외부에서 액세스 할 수있는 방법이 없으므로 프레임을 처리 할 수 ​​없다는 것입니다. 그리고 내가 main() 밖에서 정의하려고한다면, 그걸 안에서 사용할 수 없다. 그래서 dispose()를 생략하고 System.exit (0)을 사용했습니다. 이거 괜찮 니? 그것은 기본적으로 어쨌든 동일한 일을하고 있습니까? 아니면 해결해야 할 문제입니까? 그렇다면 어떤 생각입니까? 읽기에 너무 많은

감사합니다,

코디

+0

System.exit (0)은 실행중인 JVM을 종료하므로 t 모자. 해당 jvm에서 실행중인 응용 프로그램 만이 아닌 것일 수 있습니다. – fmucar

답변

5

이벤트 : 당신은 또한 쓸 수 있도록이 익명 클래스이기 때문에

class MyWindowListener extends WindowAdapter { 

    public void windowClosing(WindowEvent e){ 
     Frame frame = (Frame) e.getSource(); 
     frame.dispose(); 
    } 

} 

또는, (아마도) 생성자 내에서 선언은 또한, 둘러싸는 인스턴스에 액세스 할 수 있습니다 그것과 같은 :

class MyFrameClass extends Frame { 
    public MyFrameClass() { 
     this.addWindowListener(new WindowAdapter(){ 
      public void windowClosing(WindowEvent e){ 
       MyFrameClass.this.dispose(); 
      } 
     }); 
    } 
} 

또는 (당신의 WindowListener는 "처분"이라고 자신의 방법을 가지고 있지 않는 한) 당신은 아직도 그것을 간단하게 할 수 있습니다

public void windowClosing(WindowEvent e){ 
    dispose(); 
} 
+0

설명해 주셔서 감사합니다. 그것은 훨씬 더 의미가 있습니다. getSource의 출력을 프레임으로 캐스트하고 사용하는 일은 절대로 발생하지 않았습니다. – Keysmack

5

아니 바보 같은 질문. 그러나 가비지 컬렉터는 큰 문제가 아니기 때문에 창이 닫힐 때 정리를 실행해야하는 경우가 있습니다. 그래서 몇 가지 제안 :

프레임 닫기 이벤트는 프레임 자체에서 처리해야합니다. 예를 들어 :

this.addWindowListener(new WindowAdapter(){ 
     public void windowClosing(WindowEvent e){ 
        //code here to perform as the window is about to close. 
     } 
     }); 

그리고 난 당신이 프레임을 호출합니다 기본 방법에 대해 별도의 클래스를 만드는 것이 제안 등

당신은의 source 속성에서, 프레임에 대한 참조를 얻을 수
+0

응답 해 주셔서 감사합니다. 내 주요 방법에 대해 별도의 클래스를 사용해 보려고합니다. 그런 식으로 훨씬 깨끗해 보입니다. – Keysmack

0
This is used to close Jframe with an event handler. 


current Jframe 

public class LoginForm extends JFrame 
{ 

    LoginForm() 
    { 
     //Some code for Jframe and its components. 
     if(Condition) 
     disposewindow(); 
    } 




private void disposewindow() 
     { 
      WindowEvent closingEvent = new WindowEvent(LoginForm.this, 
                  WindowEvent.WINDOW_CLOSING); 
      Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent); 

     } 



//you can can use for alternate of dispose()event and it post some event handler **Closing event** , 

// if we can use this closing event to open new window with conditions. 

//It means closing child window with closing event, get this flag in main window to make main window as Disable or Enable state 

}

// 부모 창에서을 @Override

public void windowClosing(WindowEvent arg0) { 

     // TODO Auto-generated method stub 
     this.frame.disable(); 
    }