2011-12-19 6 views
0

죄송하지만 제 영어는 잘 못됩니다.Jbutton에 대한 액션으로 교차 리디렉션

글쎄, 내가 코드에서 상호 참조를 가지고 있기 때문에 나는 개념 상 문제가있다. 나는 내가 다른 것을 할 수 있는지 알고 싶다.

public class JFrameVcView extends JFrame { 
     ... 
     private void init() { 
       ... 
       JButton jButtonFilter = new JButton(new FilterAction(this, "Filter")); 
       ... 
     } 
    } 

내 FilterAction 클래스보기가 좋아 :

나는 프레임이

public class FilterAction extends AbstractAction { 
private final JFrameVcView fenetre; 
private final List<JTextField> textFieldList; 

public FilterAction(JFrameVcView fenetre, String texte) { 
super(texte); 
this.fenetre = fenetre; 
this.textFieldList = fenetre.getTextFieldList(); 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
for (JTextField jtf : textFieldList) { 
    System.out.println("name : " + jtf.getName() + " value : " + jtf.getText()); 
} 
} 

}

내 행동이 JFrameVcView에 대한 참조를 가져시피을하지만, 전화 JFrameVcView있어 이 행동. 그래서 나는 이것이 좋은 해결책이 아니라고 생각합니다. 그런데 내가 막히면 어떻게 할 수 있는지 알 수 없습니다.

감사합니다. Shoxolat.

답변

0

그런 콜백 참조를 갖는 것이 일반적입니다. 예를 들어, 익명의 내부 클래스가 사용될 때마다 익명의 ActionListener 인스턴스는 외부 클래스에 암시적인 참조를 가지며, 이것은 액션을 구성하는 JFrame 또는 JPanel입니다.

당신이 가진 문제는 액션의 생성자가 JFrame의 요소에 액세스하려고 시도하는데,이 요소는 아직 생성 단계이기 때문에 사용할 수 없다는 것입니다.

가장 깨끗한 방법은 아마도 프레임을 구성하는 것이고 프레임이 완전히 구성되면 프레임을 참조하는 모든 동작을 만듭니다. 이 방법은, 당신은 사용할 수의 이전 프레임을 탈출하지 않도록합니다

private JFrameVcView() { 
    // calls the init() method which creates all the components 
} 

private void createActions() { 
    // create the actions and sets them on the buttons. 
} 

public static JFrameVcView createFrame() { 
    JFrameVcView view = new JFrameVcView(); // calls the init() method which creates all the components 
    view.createActions(); // when this method is called, the frame has all its buttons 
    return view; 
} 

또한 오히려 생성자를 호출하는 대신 액션의 actionPerformed 메소드에 fenetre.getTextFieldList()를 호출 할 수 있습니다.

+0

답장과 예제를 보내 주셔서 감사합니다. 따라서 상호 참조가있는 것이 정상입니다. 가장 깨끗한 방법을 가져 주셔서 감사합니다. 사용하겠습니다. – Shoxolat

관련 문제