The PlayBalloon Applet
Applet that shows how to use your own objects/classes and also how to extend them.
/*
Java applet to demonstrate the use of classes.
This is the exmample from Chapter 10 of Bell & Parr
*/
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class PlayBalloon extends Applet implements ActionListener {
private Button grow, shrink, left, right;
private ColoredBalloon myRedBalloon;
public void init() {
makeGui();
myRedBalloon = new ColoredBalloon(255, 0, 0);
} // init
public void paint(Graphics g) {
myRedBalloon.display(g);
} // paint
public void actionPerformed(ActionEvent e) {
if (e.getSource() == grow)
myRedBalloon.grow();
if (e.getSource() == shrink)
myRedBalloon.shrink();
if (e.getSource() == left)
myRedBalloon.left();
if (e.getSource() == right)
myRedBalloon.right();
repaint();
} // actionPerformed
private void makeGui() {
grow = new Button("Grow");
add(grow);
grow.addActionListener(this);
shrink = new Button("Shrink");
add(shrink);
shrink.addActionListener(this);
left = new Button("Left");
add(left);
left.addActionListener(this);
right = new Button("Right");
add(right);
right.addActionListener(this);
} // makeGui
} // PlayBaloon
//---contents of Balloon.java------
/*
The Balloon class is defined here
*/
import java.awt.*;
class Balloon {
int diameter = 10;
int xCoord = 20, yCoord = 50;
public void display(Graphics g) {
g.drawOval(xCoord, yCoord, diameter, diameter);
} // display
public void left() {
xCoord = xCoord - 10;
} // left
public void right() {
xCoord = xCoord + 10;
} // right
public void grow() {
diameter = diameter + 5;
} // grow
public void shrink() {
diameter = diameter - 5;
} // shrink
} // Balloon
class ColoredBalloon extends Balloon {
private Color color = new Color(200, 200, 200); // some default color
public ColoredBalloon(int r, int g, int b) {
color = new Color(r, g, b);
}
public void display(Graphics g) {
g.setColor(color);
g.fillOval(xCoord, yCoord, diameter, diameter);
} // display
} // ColoredBalloon