11
Risky Behavior
Stuff happens. The file isn’t there. The server is down. No matter how good a
programmer you are, you can’t control everything. When you write a risky method, you need
code to handle the bad things that might happen. But how do you know when a method is
risky? Where do you put the code to handle the exceptional situation? In this chapter, we’re
going to build a MIDI Music Player, that uses the risky JavaSound API, so we better find out.
12
A Very Graphic Story
Face it, you need to make GUIs. Even if you believe that for the rest of your
life you’ll write only server-side code, sooner or later you’ll need to write tools, and you’ll
want a graphical interface. We’ll spend two chapters on GUIs, and learn more language
features including Event Handling and Inner Classes. We’ll put a button on the screen,
we’ll paint on the screen, we’ll display a jpeg image, and we’ll even do some animation.
class with a
risky method
t
h
r
o
w
s
a
n
e
x
c
e
p
t
i
o
n
b
a
c
k
class Cow {
void moo() {
if (serverDown){
explode();
}
}
}
your code
class Bar {
void go() {
moo();
}
int stuff() {
x.beep();
}
}
calls risky method
1
2
class MyOuter {
class MyInner {
void go() {
}
}
}
The outer and inner objects
are now intimately linked.
These two objects on the
heap have a special bond. The
inner can use the outer’s
variables (and vice-versa).
i
n
n
e
r
o
u
t
e
r
Your fi rst GUI 355
Getting a user event 357
Implement a listener interface 358
Getting a button’s ActionEvent 360
Putting graphics on a GUI 363
Fun with paintComponent() 365
The Graphics2D object 366
Putting more than one button on a screen 370
Inner classes to the rescue (make your listener an inner class) 376
Animation (move it, paint it, move it, paint it, move it, paint it...) 382
Code Kitchen (painting graphics with the beat of the music) 386
Exercises and puzzles 394
Making a music machine (the BeatBox) 316
What if you need to call risky code? 319
Exceptions say “something bad may have happened...” 320
The compiler guarantees (it checks) that you’re aware of the risks 321
Catching exceptions using a try/catch (skateboarder) 322
Flow control in try/catch blocks 326
The fi nally block (no matter what happens, turn off the oven!) 327
Catching multiple exceptions (the order matters) 329
Declaring an exception (just duck it) 335
Handle or declare law 337
Code Kitchen (making sounds) 339
Exercises and puzzles 348