I Hate Java
I Hate Java

Reputation: 27

How can my MVC listener distiguish between different buttons

This is my first time trying the MVC design pattern, and I'm trying to figure out how my controller class can tell, when a different button is pressed, and how it can then pass it on to model

public void addController(ActionListener controller){
    System.out.println("View      : adding controller");
    btnGo.addActionListener(controller);
    btnBack.addActionListener(controller);
} 

That is how I send it to the controller:

public void actionPerformed(java.awt.event.ActionEvent e){
    System.out.println("Controller: acting on Model");
    model.actionGo();
} 

I have only managed to be able to perform one action.

Upvotes: 0

Views: 52

Answers (2)

witchedwiz
witchedwiz

Reputation: 305

can you give us some additional information in terms of context? for example I use spring and I can do something like this:

    @RequestMapping(value = "/updateAcerAccount", method = RequestMethod.POST)
    public String updateAcerUser(@ModelAttribute("userModel") UserViewBean bean, @RequestParam(required = false) String submitType, HttpServletRequest request, Model model) {
    if (submitType != null && "extend".equals(submitType))
     {
      // do something on extend
      return "targetPage";
     }
     else {
      //dosomething else on submit
      return "targetPage2";
     }
    }

with submittype being associated to these two buttons in an html page..

    <button type="submit" class="btn btn-danger" name="submitType" id="saveUser" value="extend">Resend Link</button>
    <button type="submit" class="btn btn-success" name="submitType" id="saveUser" value="submit">Submit Decision</button>

hence give us some context, it's a webapp, a "desktop" application? what technology you use? ..

worst case scenario you can go with determining method branch based on the "originator" of the call, but really.. that's not something i'm overly a fan of...

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37604

You can use if cases in the listener to differ the buttons etc.

public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == btnGo){
        //perform action when btnGo clicked
    }
    if (e.getSource() == btnBack){
        //perform action when btnBack clicked
    }
}

Upvotes: 1

Related Questions