Pertemuan 11
Pertemuan 11
3
The Bouncing Ball Applet
• Each click of the Step
button advances the ball
a small amount
• The step number and
ball position are
displayed in the status
line
4
The Ball Applet: Controller
• The Controller tells the Model what to do
• The Controller tells the View when it needs to
refresh the display
• The Controller doesn’t need to know the inner
workings of the Model
• The Controller doesn’t need to know the inner
workings of the View
5
Controller
Controller
Create Model Model
Create View
GiveView access to View
Model
Tell Model to advance
Tell View to repaint
6
Controller I
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
// more...
7
Controller II
public void init() {
// more...
8
Controller III
// Attach actions to components
stepButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent
event) {
model.makeOneStep();
}
});
// more...
9
Controller IV
// Tell the View about myself (Controller) and
// about the Model
model.addObserver(view);
view.controller = this;
// more...
10
Controller V
public void start() {
model.xLimit =
view.getSize().width - model.BALL_SIZE;
model.yLimit =
view.getSize().height - model.BALL_SIZE;
repaint();
} // end of start method
11
Controller (repeated)
Controller
Create Model Model
Create View
GiveView access to View
Model
Tell Model to advance
Tell View to repaint
(via Observer)
12
Key points
• A Model does the “business logic”
– It should be I/O free
– Communication with the Model is via methods
– This approach gives maximum flexibility in how the model is used
• The Controller organizes the program and provides input
(control) to the Model
• The View displays what is going on in the model
– It should never display what should be going on in the model
– For example, if you ask to save a file, the View shouldn’t itself tell you that
the file has been saved—it should tell you what the model reports
• Especially in small programs, the Controller and View are often
combined
13
Terima Kasih