6.096 Class Notes -
Friday, October 10, 1997!: Events!
(by Jennifer Chung)
2.5 handouts:
documentation project (plus printout of files listed on that page)
course notes (beware! text may be changed!)
Miscellaneous Information.
- the documentation problem set deals with what goes on inside entitities rather than between entities in a system.
- no lab next week! :(
- assignment is due 20 Oct. assignment: document the code.
- the code solves the calculator problem set, but in a different way than what you probably did.
Today: Events, java.awt
The following lecture has been designed as a post-Calculator problem set discussion.
- remember the jukebox?
- remember the CoinChangeCounter?
- There are 3 requests to the jukebox:
- deposit coin
- "return" coin [NOT the same return which is a JavaWord(tm)]
- play song/commit money
- So what does each component need to do in order to carry out those three jobs?
- Assume that we already have the following methods:
- bank.store( int $ )
- CoinReturn.giveBack( int $ )
- Let's set up some Infrastructure!
public class MoneyMgr {
private int balance; // keeps track of current,
// undeposited money.
private Bank bank;
private CoinReturn coinRet;
// constructor
public MoneyMgr( Bank b, CoinReturn c ) {
// "etc."
}
}
(digression1 about communication)
- Let's look at the requests again. How do the requests get generated? What do you do for each request?
- deposit coin --> add to balance
- return coin --> CoinReturn. balance to 0.
- play song --> take 25 cents (cost of one song) from balance and store somewhere else. if there's not enough money in balance, throw an exception. [alternatively, an if-statement could be used]
- Okay, now let's play with the methods.
/* the following *does not* check for wrong
coins, negative numbers, etc. */
public void handlerDeposit( int coin ) {
this.balance = this.balance + coin;
}
public void handlerCoinReturn( ) {
this.coinRet.giveBack( this.balance );
this.balance = 0;
}
(digr2 about fields, etc.)
public void handlerCommit( ) throws NotEnuf$Exception {
if( this.balance >= 25 ) {
this.bank.store( 25 );
this.balance = this.balance - 25;
} else {
throw new NotEnuf$Exception( );
}
}
// re: the "25" -> it would make sense to have a
// constant (field) at the top of the class
public Static final int SONG_PRICE = 25;
// in which case the method would change to
public void handlerCommit( ) throws NotEnuf$Exception {
if( this.balance >= SONG_PRICE ) {
this.bank.store( SONG_PRICE );
this.balance = this.balance - SONG_PRICE;
} else {
throw new NotEnuf$Exception( );
}
}
// which, although longer to type, is much better style. If
// the song price changed, for instance, it would be easier
// to just change the constant's value than to go through
// and find *every* place with the number 25 and change it
// (in which case you might accidentally mess up a "25" with
// a different purpose, or skip a few "25"s). Also, the
// "SONG_PRICE" is more descriptive than random "25".
- Another way of writing all that, of course, would be to have a run method.
In a run method,
- you continuously check to see if someone wants you to do something
- when you get an input, you choose what should be done.
- get input --> figure out what to do --> do it (wash, rinse, repeat)
- continuously loops and loops
- but! haven't created the "what input do you want me to practice?" yet.
- one way to write that may be with a run method containing switch statements? But that's middle management!
- someone else is generating the "oh i want you to..."
- someone else is performing the action ("deposit coin", etc.)
- sometimes, the request is just sitting there, and you have to get it.
- make your choice: do you sense whenever you want, or do you sense only when something "wakes you up" (prompts you; event-driven)?
- the loopy method is like "busywaiting"/"polling":
- do you have a coin for me?
- if not, then I won't do anything until there IS a coin. (5 min. later: do you have a coin for me? 7 min. later: do you have a coin for me? 10 min. later: do you have a coin for me?)
- alternatively, it could return false and loop back to check again.
- the other method, the latter one, sez: "Here! Wake me up when a coin comes, okay? zzz..z..."
- (mini-digression3)
- because the processes are (in the latter case), triggered by an EVENT, (yeah, you picked the latter case) this is a different way for constantly checking, in what is NOT a self-animation... called... (ta-da!)
Let's review.
(before) Interactive Control Loop.
(after) Event driven Programming. (grovel)
(language digression4)
But now, let's focus on...
JAVA.AWT
keep in mind that this is assuming that at the top of all of the following classes, it says "import java.awt"...
(nutshell digression5)
okay, I lied. Back to Event-driven programming.
The idea?
- There's a magical pokey stick (no, not the Japanese snack) which hits you -- wake up!
- It can ask you more than one request at the same time (that is, make multiple calls at one moment) -- more on that in a week and a half erso.
- It tells you that it's time to handle this, that, and the other thing.
- So, the glorious handler*() methods we just wrote are called... EVENT HANDLERS! (that explains the "handler" fetish in the names)
- Not only will they wake you up, they'll give you the coin you need to push the method on (get a shoebox).
- Who tells you "a coin was deposited" will tell you which coin.
- Or, it will tell you that a mouse was clicked. where? here.
- Think of it as an impatient child. Father has told the child that he will play chess with her at noon. Father takes a nap. The clock shows "noon", and the child anxiously wakes up Father. Not only does she wake up Father, but she brings a chess board and pieces with her.
And now, the infamous java.awt package.
WARNING!: THE NUTSHELL BOOK HAS '#' METHODS TO INDICATE THAT THEY DON'T WORK IN JAVA 1.1 (THEY'RE FROM 1.0)
- Today: Three parts to the AWT tool kit, and more on part 2, on Wednesday.
- Components, Graphics (+ painting!), and Events (of which there will be more on Wednesday. ish.)
- So... what is a component?
(gui digression6)
- java.awt Component -- "the Granddaddy of GUIs" (well, maybe not menus). All others are derivations/children.
(abstract class digression7)
To the end: Graphics and stuff.
An example of canvas at work.
public class RectCanvas extends java.awt.Canvas {
Graphics g;
g.drawRect(10, 10, 35, 15); // magic numbers, but
// should be constants
- this is measured in pixel coordinates; the first 10 is 'x', the second 10 is 'y', the 35 is height, and the 15 is width
- it has component-relative screen coordinates.
- you want to be notified when the canvas should be repainted -- which is whenever a window blocking the canvas goes away.
thus:
public void paint( Graphics g ) {
g.setColor( Color.pink );
g.drawRect( 10, 10, 35, 15 );
}
}
end of canvas definition.
and hence the original and the paint method get:
- if this were an extended applet and not a canvas, it would do applet things.
- but! you need to make the paint method called ONLY by java! (because you don't know what to graphic it)
- to paint: call this.repaint( ) <-- no parameters!!
- you call this.repaint( ) and in turn java will repaint it.
- NEVER call paint( Grahpic g ); it will call your paint method automatically when:
- something stops blocking the painted surface
- you call repaint
- Yay! We can build awt things now!
On Wednesday: how to handle other kinds of events (ie, mice)...
Digressions, Side Comments, Etc.
digression 1.
To communicate between objects, one utilizes method invocation.
go back
digression 2
- this is what instances for MoneyMgr and CoinReturn would look like.
- MoneyMgr contains a shoebox, "balance", with the value 25 (or "whatever").
- CoinReturn contains a method, "giveBack".
- when giveBack is called, it creates a new shoebox that contains the value in balance, not just using the balance shoebox. That means that the temporary shoebox is the object who, in the handlerCoinReturn code, gives 25 cents back to the user. GIVEBACK DOES NOT DIRECTLY TAKE 25 CENTS FROM BALANCE. That is why in the handlerCoinReturn code, we must set balance back to the value of 0. After the giveBack rule is gone, the temporary shoebox (which returned 25 cents to the user, or whomever) goes away.
Further details (re: scoping).
- re: temporary shoeboxes. In a rule/method, it exists and is there until the method ends.
- parameters or inside-declared variables go away at the end of methods. (remember finger exercises from lab3?)
- only fields get kept throughout the entire class.
- having many fields isn't necessarily a bad thing, but it may be bad to wrongly differentiate between a field and a temporary invocation (of a variable that only exists in one method), AND it may be a good idea to collect some fields into one object type, to keep track of all of them together (for instance, instead of having separate fields:
- int quarters;
- int dimes;
- int nickels;
- int pennies;
it may just be easier to have
where, in a previous class, Coins was defined as something which held quarters, dimes, nickels, and pennies, in that order).
- an example of scope.
in
void handleDesposit( int coin ) {
// etc.
}
"coin" only lasts for the scope of the method.
- giveBack can't change the object "balance" is stuck to. What's pointed to goes to the method, not the label.
go back
digression 3.
Laugh during class, darnit! [ to las ~ :D ]
go back
digression 4.
Java beans are for visual programs (VBasic, etc.) but constructing GUIs. They're centered around event-driven programs.
[notetaker's note: i have no idea what this means any more]
go back
digression 5.
(a shameless plug for Java in a Nutshell)
Perhaps now is the time to purchase (a new used car? a house?) a Java documentation-type book. One can find information in such books, relevant information, such as further information about java.awt in such texts as Java in a Nutshell; it is reminded, of course, that one may find said information in the form of documents on the web, too. But have something handy for those long lonely nights of coding. Recommended: the nutshell book. Buy it for the tiger cover! Keep it for the awt docs!
go back
digression 6.
What's a GUI? [pron: "goo-ey"]
- we see them all the time (but in my day, it would be explained because it was never seen, and now it's explained because it's always seen :)
- WIMP --> Windows, Icons, Mice, Pointing --> the dominant paradigm.
- the good ol' days had... TELETYPE! A terminal window which only has paper. (ehh?!)
- okay, fine, we still have athena%esque DOSy prompt-things... but isn't it neater to draw pictures?
- ex: Alice's Restaurant? circles, lines, arrows?
- Buttons!
- ooh! java.awt lets us do gooey things! if not, then probably text-based, type-to-shell only.
- text-only COULD be used, but windows has been used and mostly will be.
go back
digression 7.
- Somewhere between an interface and a class.
- may have no-body methods.
public void run;
versus
public void run{ };
and then there's
public abstract void run;
- NO body. specification only.
- can't call it; wouldn't know how to do it.
- interface methods are always abstract; Java automatically thinks the word "abstract", however.
- can't make an instance of this [ie, one of those "new _____" things]
- but! can use it as a type (like a peephole unto more extensive properties)
- can have real fields, some method bodies.
- there are various other things, too, which won't be detailed here.
- abstract classes -- nonstatic fieldable like a class, but instanceless like an interface...
go back
Questions? E-mail me.
~/www/10oct97.html | jsmthng@mit.edu | revised October 14,1997!