Joseph
Joseph

Reputation: 119837

Hijacking listeners in Java, passing in additional parameters

I am building a simple app and I am implementing it in a simple MVC pattern where the controller adds event handlers to the view. Here's a sample controller code attaching a handler to the UI.

Basically, the code adds an event handler when the UI's save button is clicked. The UI contains the name and id number entry. What I wanted to happen is to pass the name and id number into the actionPerformed function.

ui.onAddStudent(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.print("test");
    }
});

And the receiving function in the UI (in another file) is the following.

public void onAddStudent(ActionListener handler){
    //something missing here
    addStudent.addActionListener(handler);
}

I am not really into Java because it's not my forte. I actually do JavaScript. Now, a similar handler In JavaScript, one can use the call() or apply() method to call the handler and pass in additional parameters. If the above code was in JS, it would be like

//in the controller
ui.onAddStudent(function(event,id,name){
    //I can use id and name
});

//in the UI
ui.onAddStudent = function(handler){
    //store into a cache
    //add handler to the button
}

//when student is added (button clicked)
handler.call(this,event,id,name);

How do I do the same thing in Java?

Upvotes: 0

Views: 711

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

You can define your own Actions too, and set those to the buttons (constructor argument or setAction) and other components.

Extend AbstractAction for that.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691655

You have two choices:

  • let it as it is, and have the controller get the ID and name from the GUI (and that is the easiest and simplest solution, IMHO)
  • use your own Event and Listener types, containing this information. For example:

    public class StudentAddedEvent {
        private long ID;
        private String name;
        ...
    }
    
    public interface StudentAddedListener {
        void studentAdded(StudentAddedEvent event);
    }
    

The UI would register an ActionListener on the button, and this action listener would do:

@Override
public void actionPerformed(ActionEvent e) {
    long id = getIdInGui();
    String name = getNameInGui();
    StudentAddedEvent event = new StudentAddedEvent(id, name);
    for (StudentAddedListener listener : studentAddedListeners) {
        listener.studentAdded(event);
    }
}

Upvotes: 3

Related Questions