2012-08-24 4 views
3

자바 스윙을 프로그래밍 할 때 자바 스윙 스레드가 스레드 안전하지 않기 때문에 Java 구성 요소를 Java 이벤트 큐에 넣어야한다는 내용을 읽었습니다.Java 이벤트 큐 : JFrame의 구성 요소를 업데이트하는 방법

그러나 Event Queue을 사용할 때 구성 요소 속성을 업데이트하는 방법을 알지 못합니다 (예 : 레이블 텍스트를 설정하거나 변경할 수 있습니다 ..). 여기 내 코드입니다 :

public class SwingExample { 

    private JLabel lblLabel;  
    SwingExample(){ 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 

     lblLabel = new JLabel("Hello, world!", JLabel.CENTER); 
     frame.getContentPane().add(lblLabel); // adds to CENTER 
     frame.setSize(200, 150); 
     frame.setVisible(true); 

    } 

    public void setLabel(){ 
     lblLabel.setText("Bye Bye !!!"); 
    } 



    public static void main(String[] args) throws Exception 
    { 
     SwingExample example = null; 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       example = new SwingExample(); // ERROR : Cannot refer to non-final variable inside an inner class defined in different method 
      } 
     }); 

     // sometime in the futures, i want to update label, so i will call this method... 
     example.setLabel(); 
    } 

} 

내가 SwingExample example = new SwingExample();을 작성하는 경우 나 오류가 다시 나타나지 않습니다, 알고,하지만 난 것을 사용하는 경우, 나중에 example.setLabel을 처리 할 수 ​​없습니다.

이 오류 및 해결 방법에 대해 알려주십시오.

감사합니다 :)

+0

@AndrewThompson'example.setLablel' GUI 만 업데이트하는 예제입니다. 이 클래스를 업데이트하려면'SwingExample' 객체를 저장해야합니다. – hqt

+0

소스를 잘못 읽었습니다. 첫 번째 코멘트는 무시하십시오. 더 나은 도움을 받으려면 두 가지 수업으로 [SSCCE] (http://sscce.org/)를 게시하십시오. –

+0

@AndrewThompson'example.setLabel' 행에 주석을 추가하기 때문에 사실, 다른 클래스의 다른 상황이나 외부의 다른 메소드의 경우 "언젠가"에 언젠가 레이블 텍스트를 설정하고 싶습니다. – hqt

답변

3

필드로 SwingExample 인스턴스를 가짐으로써, 당신은 final을하지 않고 내부 클래스 내부를 참조 할 수 있습니다.

public class SwingExample { 

    private JLabel lblLabel;  
    private static SwingExample instance;  

    SwingExample() { 
     // code omitted 
    } 

    public void setLabel() { 
     lblLabel.setText("Bye Bye !!!"); 
    } 

    public static void main(String[] args) throws Exception { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       instance = new SwingExample(); 
      } 
     }); 

     // ... 

     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       instance.setLabel(); 
      } 
     }); 
    } 
} 
관련 문제