How is a Java Swing application organized to achieve MVC architecture?
问题:
回答1:
See: A Swing Architecture Overview
回答2:
i would categorize my classes:
- object classes: to represent objects
- functionality classes: to provide functionality. for instance, methods to read/write files or methods to make calculations possibly using some object classes
- and GUI classes (using Swing) which will be what the user will see. these classes will do what the functionality classes provide.
回答3:
Your project must be consist at least of three entities: your model
, your view
and yor controller
.Your model represents your data, view is a view for your data and controller is something that creates both view and controller.
Let's suppose you've a rectangle and want to build a GUI that shows the area of the rectangle when user types its side.
Your model must extends Observable
class, in this way you mark class Square as model in your MCV architecture
.
public class Square extends Observable {ecc....}
when you set the side, you have to set the state of the model as changed and notify observers which are listening on your model, such as:
public void setSide(double side) {
this.side=side;
setChanged();
notifyObservers();
}
PS: setChanged()
and notifyObservers()
are provided by Observable
class.
Now the second step, your View must implement Observer
interface, so you mark this as listener for model's change. Implementing Observer forces you to write update
method.
public class Square_View implements Observer {
JLabel area;
......
@Overried
public void update (Observable o, Object arg1) {
Square square=(Square)o;
area.setText(square.getArea());
}
Well, as soon as your square's side changes, a notification is triggered and update method is invoked.
Now the controller
, the mind of MVC architecture:
public class MyProgram extends JFrame {
... somewhere in your class
Square s=new Square();
Square_View sv=new Square_View();
s.addObserver(sv);
}
As I said before, you create both model and view and register the view as observer for your model.