1

I would like to optimise my Java programming code towards a better separation of model and view.

At the moment I have Panels which represent the view and POJOs and DAOs representing the model.

Is it possible to separate the model component DaoUser from the View Panel?

// Panel User
class UserPanel extends JPanel{
   DaoUser daoUser = new DaoUser;
   User user = daoUser.findUser(current_id);
   JTextField tf = new JTextField();
   tf.setText(user.getName());
}

//POJO User
class User{
 int id;
 String name;

Getters and Setters ..
}

// Dao User
class DaoUser{
 public void saveUser(User user)
 public User findUsers();
 public List<User> listUsers()

}
user3703592
  • 160
  • 8
  • 2
    Yes, by adding a manager/controller layer. Btw, a better name for DaoUser would be UserDAO. – Manu Jul 15 '15 at 08:06
  • 2
    *"Is it possible to separate the model component DaoUser from the View Panel?"* - Yes. Simply pass an instance of `DoaUser` to `UserPanel` rather the creating an instance of it. Also you really should be making use of `interfaces` over classes to describe the expected behaviour – MadProgrammer Jul 15 '15 at 08:06
  • Use one of the observer patterns suggested [here](http://stackoverflow.com/a/3072979/230513). – trashgod Jul 15 '15 at 10:52
  • A question... the MVC pattern lets you to update the view if your model changes... in this case, what's your change?? – user2896152 Jul 16 '15 at 12:12

1 Answers1

1

If I were you, I would do something like this:

class DaoUser extends Observable {
  //other methods
  public User findUsers (int id_user) {
    //find your user. Once you find it
    setChanged();
    notifyObservers(user_found);
  }
}

and in your view, you should do:

class UserPanel extends JPanel implements Observer {
  tf = new JTextField();
}

@Override
public void update(Observable o, Object ob) {
  User u=(User) ob;
  tf.setText(u.getName());
}

I hope this could help you

user2896152
  • 762
  • 1
  • 9
  • 32