Object Oriented Programming LP3 2004
Download
Report
Transcript Object Oriented Programming LP3 2004
Object Oriented
Programming
Lecture 9:
GUI Framework –Overview of AWT and
Swing, The composite Design pattern
Examples: Maxit game
www.hh.se/staff/jebe/oop2005/
Graphical User Interfaces in Java
There are two major packages in the Java
GUI Framework:
Abstract Windows Toolkit (AWT)
Provides basic support for GUI development
AWT components are ”heavyweight” (Looks and
behaves as the underlying OS windows system)
SWING
Extension of AWT, a bit more sophisticated and
extensive than AWT
Most components are ”Lightweight” (Java
runtime environment, not OS dependant look)
Four ”main” class categorys
Components
Each visible GUI object is of Component type
Layoutmanagers
Determines how components are placed within an
outer container
Events and Eventlisteners
Java user interaction is event driven (inputs or
actions)
Graphics and Imaging Classes
Provides methods to draw images, texts and shapes
Design patterns widely used in
the GUI Frameworks
Common used patterns are:
Strategy
Layoutmanager is a strategy pattern for placing
components
Some concrete strategys: FlowLayout,
BorderLayout, GridLayout etc...
Template
Example: Component, MouseAdapters...lettings
us define methods like paint, update, dealing
with mouse actions. etc.
Composite
Combines several components uniformly
Design pattern: Composite
The composite pattern is a pattern for
hierarchial tree structures of objects
Components that in turn contain other
components (a hierarchy of objects)
We can treat a combination of several
components as one uniform object
Example: A ButtonPanel containing Buttons..
A Frame with Buttons and Drawing space
Our search engine in the Laboration:
We can easily change between different types of
UIs
These UIs are uniform objects to the engine
Structure of the Composite pattern
Client
Component
operation()
add(Component)
remove(Component)
getChild(int)
Leaf
operation()
Component
operation()
add(Component)
remove(Component)
getChild(int)
LayoutManager
Container
LayoutManager
BorderLayout
LayoutManager2
CardLayout
GridBagLayout
FlowLayout
GridLayout
Event handling in Java
Users interact with a program by
trigging Event objects
Clicking a mouse, Typing text etc...
In Java, we use EventListeners to
detect Events so we can assign the
proper action
When an Event occur, program
execution is transfered to the listener
object (ex. actionPerformed(Event e))
The Event handling process
1.) When an Event has ocurred, JVM
determines source and type
2.) If there is any Listener for this
event, an Action Event is instantiated
3.) For each Listener that match the
event, JVM calls the event handling
method, passing the Event object
GUI Design study: The Maxit Game
View – Model - Controller
The Game is factorized into a View,Model and
Controller design
Recall the Pen & Paper exercise
Paper
Records the ”state” of the paper (a Vector with Line
objects)
Methods to add, remove Lines etc..
PaperView
How the presentation of the Paper model is made on
the screen
Separating the display from the implementation
Let us more easily change the UI
In Pen & Paper we elaborated with changing the view to
text based output
The Maxit Game
Maxit
MaxitModel
MaxitView
MaxitController
The Model
Maintains the Game data
Number of players
Game board data
State of the game (chosen numbers)
Initalizes new games
Human/computer opponent
Compute new random table values
Compute the artificial players move
The View
Implementation of the User Interface
Settings Panel
Skill of the computer player
Control Panel
Nbr of players, new game, statistics
Info panel
Current player scores
Game board canvas
Numbers and grid
The Controller
The controller ”dispatches actions” from the
user, to the model and the view (calling
apropriate methods ”to do the job”)
Button and Panel actions
Calls the proper methods to change a state
when a button is pressed (new game, number of
players, statistics etc..)
Game board actions
Check if a move is legal and update the model
and the view (Score etc..)
The game structure in Java
Import java.awt.*;
Import java.applet.*;
Public class Maxit extends Applet{
private MaxitModel theGame;
private MaxitView userInterface;
private MaxitController controller;
Game model
Game View
Game controller
public void init(){
int size = new Integer(getParameter(”size”)).intValue();
int side = new Integer(getParameter(”side”)).intValue();
setBackground(Color.lightGray);
}
}
theGame = new MaxitModel(size);
userInterface = new MaxitView(size, side, theGame);
controller = new MaxitModel(theGame, userInterface);
The Model Class
State of the game
Calculate and store the game board
values
Fill a 2D array with random numbers
Store information of played numbers
A 2D array that takes values {player1,
player2, free}
Keep track of current row, column
Current players choice, update score and
switch players turn
The data structures in the Model
Class MaxitModel{
private int[][] theValues;
private int[][] who;
private int cRow,cCol;
private int size;
Board values
Chosen numbers
Selectable row, col
private Random generator;
private int player;
private int[] score;
public static final int PLAYER_1 = 0;
public static final int PLAYER_2 = 1;
public static final int FREE = 1;
}
...
Current player
Score
The methods in the model
Class MaxitModel{
...
public MaxitModel(int s)
public void play(int r, int c)
public void sameGame()
public void newGame()
}
public
public
public
public
public
public
public
public
public
public
public
boolean gameOver()
int getWinner()
boolean isLegal(int r, int c)
int getSize()
int getCRow()
int getCCol()
boolean isFree(int r, int c)
int getWho(int r, int c)
int getValue(int r, int c)
int getScore(int i)
int getPlayer()
Mutators - Changes
the state of the game
as we play
Accessors – used by
other components to
check the state as the
game is played (View,
Controller)
The game controller class
Controls the execution flow
All game actions are mouse based
When mouse is clicked on the board...
...controller updates the Model
...and ask the View to update the screen
Controller will compute the computers
move
We need an algorithm to compute the move
Separate the choosing algorithm, the it is simple
to change different ”skill” levels
We use the Strategy pattern, separating the
chosing algorithms
The MaxitController
MaxitController
MaxitModel
Chooser
FirstChooser
MaxitView
AlfaBetaChooser
The MaxitController
Class MaxitController{
private MaxitModel theGame;
private MaxitView theInterface;
private Chooser chooser;
}
public MaxitController(MaxitModel mm, MaxitView mv){
theGame = mm;
theInterface = mv;
theInterface.addController(this);
chooser = new AlphaBetaChooser(1);
chooser.setModel(mm);
disableScoreBoard();
gameOver = false;
onePlayer = true;
}
The MaxitController Interface
Class MaxitController{
...
public void mouseClicked()
public
public
public
public
public
public
}
void
void
void
void
void
void
computerMover()
newGame()
sameGame()
setChooser(Chooser c)
setOne()
setTwo()
Compute player actions
...
Update the model
If(theGame.isLegal(row,col)){
theGame.play(row,col);
Update score on screen
theInterface.updateScores();
if(onePlayer){
No mouse actions
theInterface.disableBoard();
allowed
computerMove();
Do the computer move
}
if(theGame.gameOver() && !gameOver){
gameOver = true;
theInterface .gameOver();
}
theInterface.updateBoard();
}
Computer player
Public void computerMove{
Point choice = chooser.choose();
int row = choice.x;
int col = choice.y;
Compute next move
using our abstract
chooser strategy
int player = theGame.getPlayer();
}
if(theGame.isLegal(row,col)){
theGame.play(row,col);
theInterface.updateScores();
}
theInterface.enableBoard();
theInterface.updateBoard();
Enable the board
canvas
Redraw the current
Model state
The View
Collects and adds all the Panels and
BoardCanvas to the Applet
The View is the interface between the
model and the Graphical components
Button Panels, Settings, Control etc..
Drawing the Game board
The View is the Uniform game GUI
that the Controller ”can see”
The View structure
MaxitView
BoardCanvas
Canvas
SettingsPanel
InfoPanel
Panel
ControlPanel
View implementation
Class MaxitView{
private Settings panel settings;
private BoardCanvas board;
private InfoPanel info;
private ControlPanel control;
public MaxitView(int sz, int sd, MaxitModel m, Container a)
}
public
public
public
public
public
public
public
public
public
public
public
public
void
void
void
void
void
void
void
void
void
void
void
void
addController(MaxitController c)
updateScores()
disableBoard()
enableBoard()
updateBoard()
enableControl()
disableControl()
gameOver()
refresh()
setModel(maxitModel m)
setColorPlayer1()
setColorPlayer2()
The Panels Structure
Panel
InfoPanel
SettingsPanel
Model
ControlPanel
Controller
SkillsCanvas
Chooser
Button
BoardCanvas diagram
Canvas
MouseListener
BoardCanvas
Model
Controller
The BoardCanvas
Class BoardCanvas extends Canvas implements MouseListener{
private MaxitModel theGame;
private MaxitController controller;
...
public void update()
public int getSide()
public void addController(MaxitController c)
public void setModel(MaxitModel m)
public void setColorPlayer1(Color c)
public void setColorPlayer2(Color c)
public void paint(Graphics g)
private void paintCurrentRow(Graphics g)
private void paintCurrentCol(Graphics g)
private void drawLines(Graphics g)
private void drawContent(Graphics g)
}
public void mouseClicked(MouseEvent e)
...
public void mouseExited(MouseEvent e)