2017-12-26 45 views
0

하나의 JFrame을 만들었습니다. 이 JFrame은 일부 JButton을 포함하는 JLabel을 포함합니다. JButton에는 ActionListener (MainFrameListener라고 함)가 있습니다. arrowButton 버튼을 클릭하면 메소드가 코드에 의해 실행됩니다. 이 메소드는 이전 Button에서 모든 ActionListener를 제거합니다. foodButton.removeActionListener(new MainFrameListener());ActionListener가 두 번 호출되면 추가됨

그러나 Listener를 제거했지만 Button에는 두 개의 버튼이 있습니다. 물론 인터넷에서 문제를 해결하기 위해 검색 한 결과 하나의 버튼에 대한 Listener의 양을 보여주는 코드 줄을 발견했습니다.

System.out.println("Count of listeners: " + ((JButton) e.getSource()).getActionListeners().length); 

자바를 처음 클릭 할 때 두 개의 버튼이 있다고합니다. arrowButton을 클릭하면 다른 메뉴가 열리고 단추가 제거됩니다. 그게 내가 원하는 것처럼. arrowBackButton을 클릭하면 응용 프로그램이 나를 MainFrame으로 되돌려 보냅니다. 저건 완벽 해. 그러나 arrowButton을 다시 클릭하면 콘솔에 버튼에 등록 된 청취자가 두 명 있다고합니다. 클릭 소리는 2 번 재생됩니다.

리스너를 제거했기 때문에 이해가 가지 않습니다. Listener를 제거하는 더 좋은 방법이 있습니까?

답변

3

foodButton.removeActionListener(new MainFrameListener());foodButton에 추가 된 적이없는 새로 생성 된 개체를 제거하기 때문에 삭제되지 않습니다. 리스너에 대한 참조를 유지하고 같이 나중에 제거 :

MainFrameListener listener = new MainFrameListener(); 
foodButton.addActionListener(listener); 
//and later somewhere else 
foodButton.removeActionListener(listener); 

을하지만 내 조언은 처음에 청취자를 추가/제거 방지하는 것입니다.

+0

감사합니다. 리스너에 대한 인스턴스가 필요하다는 것을 알지 못했습니다. 잘 작동합니다 : D – PXAV