+1 vote
in Other by
Sorry for my english, i'm not good enough.

Well, at the moment i have a conception problem because i have a cross reference in my code, and i want to know if i can do something else.

I have a frame :

public class JFrameVcView extends JFrame {

       ...

        private void init() {

              ...

              JButton jButtonFilter = new JButton(new FilterAction(this, "Filter"));

              ...

       }

  }

My FilterAction class look likes :

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());

}

}

}

As you see my action get a reference on JFrameVcView, but it's JFrameVcView who call this action. So I think it's not a good solution. By the way I'm blocked, I can't find how can I do.

Thanks. Shoxolat.

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
Having a such a callback reference is common. For example, each time an anonymous inner class is used, the anonymous ActionListener instance has an implicit reference on its outer class, which is the JFrame or JPanel constructing the action.

The problem you have is that the constructor of your action tries to access elements of the JFrame, and these elements are not available yet because it's also in its construction phase.

The cleanest way would probably be to construct the frame, and once the frame is completely constructed, create all the actions referencing the frame. This way, you make sure not to escape the frame before it's usable:

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;

}

You could also call fenetre.getTextFieldList() in the actionPerformed method of the action rather than calling it in the constructor.

Related questions

+1 vote
asked Feb 1, 2022 in Other by DavidAnderson
+1 vote
asked Feb 1, 2022 in Other by DavidAnderson
...