开发者

Callback function on a JTextField

I have a presenter class and several text fields in my view.

I want my presenter to say "every textfields that are listening to me, please do something now".

BUT I don't want to use Observabe/Observer, since I already use it and I don't want to get confused.

To be a bit more specific, I want the textfields to update a Map in the presenter :

Presenter.java :

public class Presenter  {

   private HashMap<String,MyObject>开发者_开发百科 map;

   theMethod(){
     //to all text fields, please update the map

Then a textfield in a panel :

JTextField tf = new JTextField("tf 1");
tf.//add something to listen to the presenter

The beginning of the process is the method in the presenter :

  1. theMethod() is called (not by the view)
  2. theMethod() triggers a method linked to the TextFields
  3. Every methods called in every TextFields are doing something


Not really sure what you are asking but I see the following comment in your code

//to all text fields, please update the map

If you just want the text fields to update the map with the text in each text field then all you need is for the Presenter to have a LIst of all the text fields and then the presenter can iterate through the list and get the text of each text field and then update the map.

So your code would be something like:

Presenter presenter = new Presenter();
JTextField tf1 = new JTextField();
presenter.addPresentee( tf1 );

All the addPresentee() method does is add the text field to the List.


How about, instead of letting JTextFields listen to Presenter , Presenter will listen to them?

public class Presenter  {

   private HashMap<String,MyObject> map;
   private List<MyTextField> listeners = new ArrayList<MyTextField>();

   private void theMethod() {
       for (MyTextField mtf : listeners) {
           mtf.updateMap();
       }
   }

   private void addMyTextFieldListener(MyTextField listener) {
        listeners.add(listener);
   }
}


I found it !

I use a Runnable callback in the presenter.

In my view I have :

        presenter.setCallback(new Runnable(){
            public void run(){
                System.out.println("the presenter want me to do something");
                //stuff
            }
        });

And in my presenter :

private Runnable callback;

public void theMethod(){
    System.out.println("I was triggered by another far away view");
    SwingUtilities.invokeLater(this.callback);
}

Of course, I'm going to implement some List for each textfield.

In the end, I have the expected behavior :

  • Some methods dispersed in some places, but registered as callbacks in the presenter
  • The presenter now able to fire those methods when he wants to !

Great !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜