Chapter 8: Arrays 138
magicData
3
8 1 6
3 5 7
4 9 2
27 18 21 36
15 30 33 24
12 45 42 3
3
6 2 7
4 6 22 13 20
10 12 3 21 19
11 18 9 2 25
7
30 39 48 1 10 28 19
-1
Chapter 8: Arrays 139
A Polygon Person
A polygon is a multisided closed figure; a polyline is a line with an arbitrary number of segments. Both polygons and
polylines are defined by a set of points, and Java provides graphics methods for both that are based on arrays. Read section
7.8 in the text and study the Rocket example in Listing 7.16 & 7.17.
1. Draw pants to go with the shirt (they should be a different color). You will need to declare pantsX and pantsY arrays like
3. Draw hair on the head. This is probably best done with a polygon, so again you’ll need two arrays to hold the points.
5. Write a method movePerson(int x, inty) that moves the person by the given number of pixels in the x and y direction.
6. Now put a loop in your paintComponent method that draws the person three times, moving him (her?) 150 or so pixels
each time (you decide how far).
// *******************************************************************
// DrawPerson.java
public class DrawPerson
{
//———————————————–
// Creates the main frame for the draw program
//———————————————–
public static void main (String[] args)
{
JFrame frame = new JFrame (“Draw Person”);
frame.setDefaultCloseOperaton (JFrame.EXIT_ON_CLOSE);
}
}
// *******************************************************************
// DrawPersonPanel.java
//
// An program that uses the Graphics draw methods to draw a person.
// *******************************************************************
Chapter 8: Arrays 140
public class DrawPersonPanel extends JPanel
{
private final int WIDTH = 600;
//————————————–
// Constructor: Set up the panel.
//————————————–
public DrawPersonPanel()
{
setPreferredSize(new Dimension(WIDTH, HEIGHT));
}
//————————————–
// Draw person
Chapter 8: Arrays 141
An Array of Radio Buttons
File ColorOptions.java contains a program that will display a set of radio buttons that let the user change the background
color of the GUI. The file ColorOptionsPanel.java contains the skeleton of the panel for this program. Open the files and
study the code that is already there. You will note that in ColorOptionsPanel.java there is an array color containing 5 colors
already defined. Your task is to add an array of radio buttons so that a click of a radio button will cause the background of the
panel to change to the corresponding color in the color array.
1. Define colorButton to be an array of NUM_COLORS objects of type JRadioButton.
3. Recall that radio buttons must be grouped and that the selection of a radio button produces an action event. Hence you
must have a ButtonGroup object and an ActionListener. Note that the skeleton of an ActionListener named
4. Fill in the body of the actionPerformed method. This method needs to go through the buttons to determine which is
5. Test your program!
// ********************************************************************
// ColorOptions.java
//
// Uses an array of radio buttons to change the background color.
// ********************************************************************
colorFrame.pack();
colorFrame.setVisible(true);
}
}
Chapter 8: Arrays 142
// ***********************************************************************
// ColorOptionsPanel.java
//
private JLabel heading;
// ——————————————————————
// Sets up a panel with a label at the top and a set of radio buttons
// that control the background color of the panel.
// ——————————————————————
// Set up the panel
add (heading);
setBackground (Color.yellow);
setPreferredSize (new Dimension (WIDTH, HEIGHT));
// Group the radio buttons, add a ColorListener to each,
{
}
}
}
Chapter 8: Arrays 143
Drawing Circles with Mouse Clicks
File Circles.java sets up a panel that creates and draws a circle as defined in Circle.java of random size and color at each
mouse click. Each circle replaces the one before it. The code to handle the mouse clicks and do the drawing is in
CirclePanel.java. Save these files to your directory, compile them and run them and experiment with the GUI. Then modify
1. This program creates a new circle each time—you can tell because each circle is a different color and size. Write a
method void move(Point p) for your Circle class that takes a Point and moves the circle so its center is at that point. Now
2. Write a method boolean isInside(Point p) for your Circle class that takes a Point and tells whether it is inside the circle.
3. Now modify the mousePressed method of CirclesListener so that the GUI behaves as follows:
If there is no circle (i.e., it is null) and the user clicks anywhere, a new (random) circle should be drawn at the click
point.
If there is a circle on the screen and the user clicks inside that circle, the circle should go away. (Hint: To make the
4. Add bodies for the mouseEntered and mouseExited methods so that when the mouse enters the panel the background
turns white, and when it exits the background turns blue. Remember that you can set the background color with the
setBackground method.
//***************************************************************
{
JFrame circlesFrame = new JFrame (“Circles”);
circlesFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
circlesFrame.getContentPane().add (new CirclePanel());
Chapter 8: Arrays 145
// ***************************************************************
// Circle.java
public class Circle
{
private int centerX, centerY;
private int radius;
private Color color;
static Random generator = new Random();
//———————————————————
// Creates a circle with center at point given, random radius and color
//———————————————————
public void draw(Graphics page)
{
page. setColor (color) ;
page.fillOval(centerX-radius,centerY-radius,radius*2,radius*2);
}
}
Chapter 8: Arrays 146
{
private final int WIDTH = 600, HEIGHT = 400;
private Circle circle;
//——————————————————————-
// Sets up this panel to listen for mouse events.
//——————————————————————-
}
//******************************************************************
// Represents the listener for mouse events.
//******************************************************************
private class CirclesListener implements MouseListener
{
//—————————————————————
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
}
Chapter 8: Arrays 147
Moving Circles with the Mouse
File Circles.java sets up a GUI that creates and draws a circle as defined in Circle.java of random size and color at each
mouse click. Each circle replaces the one before it. The code to handle the mouse clicks and do the drawing is in
CirclePanel.java. (The files are from the previous exercise, Drawing Circles.) Save these files to your directory, compile
them and run them and experiment with the GUI. Then modify the code in CirclePanel.java so that a circle is drawn when the
user presses a mouse, but the user can drag it around as long as the mouse button is depressed. If the mouse button is released
and then pressed again, a new circle is created, which can then be dragged around. You will need to make the following
changes:
1. Write a method void move(Point p) for your Circle class that takes a Point and moves the circle so its center is at that
point. (You may have already done this in a previous exercise.)
3. Make the CirclesListener class implement the MouseMotionListener interface in addition to the MouseListener interface.
This requires two steps:
Moving a Stick Figure
The file StickFigure.java contains a class that represents a stick figure. Study the file and note that in addition to a method to
draw the stick figure there are methods to manipulate it:
The method move repositions (“moves”) the figure up or down and over (left or right) on the panel by changing the
The file MoveStickMan.java contains a program that draws a single stick figure that can be moved around and modified using
the keyboard. The file MovePanel.java represents the panel on which the stick figure is displayed. It is similar to
DirectionPanel.java in Listing 7.23 of the text. Note that the constructor adds a KeyListener and contains a call to the
setFocusable method. There is a partially defined inner class named MoveListener that implements the KeyListener interface.
Currently the MoveListener listens only for two arrow keys (left and right) and the g key. The arrow keys move the stick
figure left and right on the panel (the number of pixels moved is in the constant JUMP) and when the user presses the letter
g, the figure “grows” (increases in height by 50%). Compile, and run the program. Test out the arrow keys and the g key.
Now add code to MovePanel.java to have the program respond to the following additional key events:
When the up and down arrow keys are pressed the figure should move JUMP pixels up or down, respectively, on the
When the letter m (for middle) is pressed, the stick figure should place its arms horizontally with legs not quite as far out.
To do this the arm position needs to be 0 (0 pixels above horizontal); a value of 20 for the leg position is good.
Compile and run the program. Try out all the keys it implements.
// ***************************************************************
// StickFigure.java
private int headW; // width of the head
private int legLength; // length of the legs
private int legPosition; // # pixels the legs are up from vertical
private int armLength; // horizontal length of the arms
height = size;
// define body positions proportional to height
headW = height / 5;
legLength = height / 2;
armToFloor = 2 * height / 3;
page.setColor (color);
// draw the head
page.drawOval(baseX-headW/2, top, headW, headW);
// draw the trunk
page.drawLine (baseX, top+headW, baseX, baseY – legLength);
// to the left if over is negative) and up or down
// (down if the parameter down is positive, up if it is
// negative)
// —————————————————–
public void move (int over, int down)
{
Chapter 8: Arrays 150
}
// reset body parts proportional to new height
headW = height / 5;
legLength = height / 2;
armToFloor = 2 * height / 3;
armLength = height / 3;
}
{
armPosition = newPos;
}
}
// ********************************************************************
// MoveStickMan.java
//
// Uses key events to move a stick figure around.
// ********************************************************************
frame.setVisible(true);
}
}
// *******************************************************************
// FILE: MovePanel.java
//
// The display panel for a key events program — arrow keys are used
private final int JUMP =5; // number of pixels moved each step
// the following give the initial parameters for the figure
private final int START_CENTER = WIDTH/2;
private final int START_BOTTOM = HEIGHT – 40;
private final int SIZE = HEIGHT / 2;
setFocusable(true);
}
// ————————————–
// Draws the figure
// ————————————–
public void paintComponent (Graphics page)
{
// key causes the figure to “grow”, the s key causes
// the figure to shrink, the u key causes arms and
// legs to go up, m puts them in the middle, and d
// down.
// ————————————————–
break;
default:
}
repaint();
}
// ——————————————-
// Define empty bodies for key event methods