0

对不起我的英语,我不够好。

好吧,目前我有一个概念问题,因为我的代码中有交叉引用,我想知道我是否可以做其他事情。

我有一个框架:

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。所以我认为这不是一个好的解决方案。顺便说一句,我被阻止了,我找不到我该怎么办。

谢谢。绍索拉特。

4

1 回答 1

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;
}

您还可以调用fenetre.getTextFieldList()动作的 actionPerformed 方法,而不是在构造函数中调用它。

于 2011-12-19T10:15:27.213 回答