2014-06-05 4 views
0

제목이 짧으면 사과하겠습니다. 끝났다고 생각했지만 내 질문에 대한 요약 정보가 부족합니다.자바 부모 컴포넌트에 액션 이벤트 전달

JButton으로 구성된 JPanel 클래스가 있습니다.

스윙 구성 요소가있는 내 주요 스윙 응용 프로그램 클래스는 물론 JPanel 클래스도 있습니다. 내가하고 싶은 일은 JPanel 클래스에서 시작된 ActionEvent가 Swing 어플리케이션 클래스로 보내져 처리되도록하는 것입니다. 나는 그물과 포럼 (이것도 포함해서)에서 예제를 검색했지만, 제대로 작동하지 않는 것처럼 보입니다.

내 인 JPanel 클래스 :

public class NumericKB extends javax.swing.JPanel implements ActionListener { 
    ... 

    private void init() { 
     ... 
     JButton aButton = new JButton(); 
     aButton.addActionListener(this); 

     JPanel aPanel= new JPanel(); 
     aPanel.add(aButton); 
     ... 
    } 

    ... 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     Component source = (Component) e.getSource(); 

     // recursively find the root Component in my main app class 
     while (source.getParent() != null) {    
      source = source.getParent(); 
     } 

     // once found, call the dispatch the current event to the root component 
     source.dispatchEvent(e); 
    } 

    ... 
} 



내 주요 응용 프로그램 클래스 : 별도의 JPanel에 클래스가 있기 때문이다 쓰기를 원하는에 대한

public class SimplePOS extends javax.swing.JFrame implements ActionListener { 


    private void init() { 
     getContentPane().add(new NumericKB()); 
     pack(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     ... 

     // this is where I want to receive the ActionEvent fired from my NumericKB class 
     // However, nothing happens 

    } 
} 


이유 나는 다른 애플 리케이션에서 이것을 재사용하고 싶다.

또한 실제 코드는 내 기본 응용 프로그램 클래스에 많은 하위 구성 요소가 있으며 JPanel 클래스는 하위 구성 요소 중 하나에 추가되므로 재귀 .getParent() 호출이 발생합니다.

도움을 주시면 감사하겠습니다. 미리 감사드립니다! 건배.

+0

이 가능한 [복제] (http://stackoverflow.com/q/2159803/230513)와 같이 이벤트를 전달할 수 있습니다. – trashgod

답변

1

부모가 ActionEvent을 (를) 전달할 수 없으므로 부모에게 이벤트를 다시 넘길 수 없습니다. 그러나 귀하의 경우 귀하의 구성 요소가 조치 지원을 가지고 있는지 확인하고이를 호출 할 수 있습니다. 이 같은 것

public class NumericKB extends javax.swing.JPanel implements ActionListener { 
    ... 

    private void init() { 
    ... 
    JButton aButton = new JButton(); 
    aButton.addActionListener(this); 

    JPanel aPanel= new JPanel(); 
    aPanel.add(aButton); 
    ... 
    } 

    ... 

    @Override 
    public void actionPerformed(ActionEvent e) { 
    Component source = (Component) e.getSource(); 

    // recursively find the root Component in my main app class 
    while (source.getParent() != null) {    
     source = source.getParent(); 
    } 

    // once found, call the dispatch the current event to the root component 
    if (source instanceof ActionListener) { 
     ((ActionListener) source).actionPerformed(e); 
    } 
    } 

... 
} 
+0

감사합니다 백만 Sergiy, 나는 이것을 작동하도록 3 시간을 보냈고 한 줄은 내 문제를 해결했습니다! 단지 궁금한데, 올바른 방법은 무엇입니까? 아니면 .dispatchEvent (ActionEvent) 호출을 사용하는 것이 올바른 것입니까? – Arthur

+0

나는 결코이 방법을 사용하지 않았다. 스윙의 내부 이벤트 처리에 사용된다는 것만 알았습니다. 따라서이 메서드를 수동으로 호출하는 것은 좋지 않습니다. –