In: Computer Science
The files SpeedControl.java and SpeedControlPanel.java contain a
program (and its associated panel) with a circle that moves on the
panel and rebounds from the edges. The Circle class is in the file
Circle.java. Save the program to your directory and run it to see
how it works. In this lab exercise you will add to the panel a
slider that controls the speed of the animation.
1. Set up a JSlider object. You need to:
a) Declare it.
b) Instantiate it to be a JSlider that is horizontal with values
ranging from 0 to 200, initially set to 30.
c) Set the major tick spacing to 40 and the minor tick spacing to
10.
d) Set paint ticks and paint labels to true and the X alignment to
left.
2. Set up the change listener for the slider. A skeleton of a class
named SlideListener is already in
SpeedControlPanel.java. You need to:
a) Complete the body of the statedChanged function. This function
must determine the value of the slider, then set the timer delay to
that value. The timer delay can be set with the method setDelay
(int delay) in the Timer class.
b) Add the change listener to the JSlider object.
3. Create a label (“Timer Delay”) for the slider and align it to
the left.
4. Create a JPanel object and add the label and slider to it then
add your panel to the SOUTH of the main panel (note that it has
already been set up to use a border layout).
5. Compile and run the program. Make sure the speed is changing
when the slider is moved. (NOTE: Larger delay means slower!)
6. You should have noticed one problem with the program. The ball
(circle) goes down behind the panel the slider is on. To fix this
problem do the following:
a) In actionPerformed, declare a variable slidePanelHt (type int).
Use the getSize() method to get the size (which is a Dimension
object) of the panel you put the slider on. Assign slidePanelHt to
be the height of the Dimension object. For example, if your panel
is named slidePanel the following assignment statement is what you
need:
slidePanelHt = slidePanel.getSize().height;
b) Now use this height to adjust the condition that tests to see if
the ball hits the bottom of the panel.
c) Test your program to make sure it is correct.
DELIVERABLES :
Speedcontrolpanel.java
//
********************************************************************
// SpeedControl.java
//
// Demonstrates animation -- balls bouncing off the sides of a
panel -
// with speed controlled by a slider.
//
********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SpeedControl
{
// ------------------------------------
// Sets up the frame for the animation.
// ------------------------------------
public void static main (String[] args)
{
JFrame frame = new JFrame ("Bouncing Balls");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane.add(new SpeedControlPanel ());
frame.pack();
frame.setVisible(true);
}
}
//
******************************************************************
// SpeedControlPanel.java
//
// The panel for the bouncing ball. Similar to
// ReboundPanel.java in Listing 8.16 in the text, except a
circle
// rather than a happy face is rebounding off the edges of
the
// window.
//
******************************************************************
import java.awt.*;
import java.awt.event.*;
import javax. swing. *;
import javax.swing.event.*;
public class SpeedControlPanel extends JPanel
{
private final int WIDTH = 600;
private final int HEIGHT = 400;
private final int BALL_SIZE = 50;
private Circle bouncingBall; // the object that moves
private Timer timer;
private int moveX, moveY; // increment to move each time
// --------------------------------------------
// Sets up the panel, including the timer
// for the animation
// --------------------------------------------
public SpeedControlPanel ()
{
timer = new Timer(30, new ReboundListener());
this.setLayout (new BorderLayout());
bouncingBall = new Circle(BALL_SIZE);
moveX = moveY = 5;
// Set up a slider object here
setPreferredSize (new Dimension (WIDTH, HEIGHT));
setBackground(Color.black);
timer.start();
}
// ---------------------
// Draw the ball
// ---------------------
public void paintComponent (Graphics page)
{
super.paintComponent (page);
bouncingBall.draw(page);
}
// ***************************************************
// An action listener for the timer
// ***************************************************
public class ReboundListener implements ActionListener
{
// ----------------------------------------------------
// actionPerformed is called by the timer -- it updates
// the position of the bouncing ball
// ----------------------------------------------------
public void actionPerformed(ActionEvent action)
{
bouncingBall.move(moveX, moveY);
// change direction if ball hits a side
int x = bouncingBall.getX();
int y = bouncingBall.getY();
if (x < 0 || x >= WIDTH - BALL_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT - BALL_SIZE)
moveY = moveY * -1;
repaint();
}
}
// ***************************************************
// A change listener for the slider.
// ***************************************************
private class SlideListener implements ChangeListener
{
// ------------------------------------------------
// Called when the state of the slider has changed;
// resets the delay on the timer.
// ------------------------------------------------
public void stateChanged (ChangeEvent event)
{
}
}
}
//
****************************************************************
// FILE: Circle.java
//
// Purpose: Define a Circle class with methods to create and
draw
// a circle of random size, color, and location.
//
****************************************************************
import java.awt.*;
import java.util.Random;
public class Circle
{
private int x, y; // coordinates of the corner
private int radius; // radius of the circle
private Color color; // color of the circle
static Random generator = new Random();
//---------------------------------------------------------
// Creates a random circle with properties in ranges given:
// -- radius 25..74
// -- color RGB value 0..16777215 (24-bit)
// -- x-coord of upper left-hand corner 0..599
// -- y-coord of upper left-hand corner 0..399
//---------------------------------------------------------
public Circle()
{
radius =
Math.abs(generator.nextInt())%50 + 25;
color = new
Color(Math.abs(generator.nextInt())% 16777216);
x =
Math.abs(generator.nextInt())%600;
y =
Math.abs(generator.nextInt())%400;
}
//---------------------------------------------------------
// Creates a circle of a given size (diameter). Other
// attributes are random (as described above)
//---------------------------------------------------------
public Circle(int size)
{
radius =
Math.abs(size/2);
color = new
Color(Math.abs(generator.nextInt())% 16777216);
x =
Math.abs(generator.nextInt())%600;
y =
Math.abs(generator.nextInt())%400;
}
//---------------------------------------------------------
// Draws circle on graphics object given
//---------------------------------------------------------
public void draw(Graphics page)
{
page. setColor (color)
;
page.fillOval(x,y,radius*2,radius*2);
}
//---------------------------------------------------------
// Shifts the circle's position -- "over" is the number of
// pixels to move horizontally (positive is to the right
// negative to the left); "down" is the number of pixels
// to move vertically (positive is down; negative is up)
//---------------------------------------------------------
public void move (int over, int down)
{
x = x + over;
y = y + down;
}
//----------------------------------------------
// Return the x coordinate of the circle corner
//----------------------------------------------
public int getX()
{
return x;
}
//----------------------------------------------
// Return the y coordinate of the circle corner
//----------------------------------------------
public int getY()
{
return y;
}
}
import
java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public
class SpeedControl {
// Sets up the frame for the animation.
public static void main(String[] args) {
JFrame frame = new
JFrame("Bouncing Balls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SpeedControlPanel());
frame.pack();
frame.setVisible(true);
}
}
-----------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class SlideColorPanel extends JPanel {
private JPanel controls, colorPanel;
private JSlider rSlider, gSlider, bSlider;
private JLabel rLabel, gLabel, bLabel;
// Sets up the sliders and their labels,
aligning them along
// their left edge using a box layout.
public SlideColorPanel() {
rSlider = new
JSlider(JSlider.HORIZONTAL, 0, 255, 0);
rSlider.setMajorTickSpacing(50);
rSlider.setMinorTickSpacing(10);
rSlider.setPaintTicks(true);
rSlider.setPaintLabels(true);
rSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
gSlider = new
JSlider(JSlider.HORIZONTAL, 0, 255, 0);
gSlider.setMajorTickSpacing(50);
gSlider.setMinorTickSpacing(10);
gSlider.setPaintTicks(true);
gSlider.setPaintLabels(true);
gSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
bSlider = new
JSlider(JSlider.HORIZONTAL, 0, 255, 0);
bSlider.setMajorTickSpacing(50);
bSlider.setMinorTickSpacing(10);
bSlider.setPaintTicks(true);
bSlider.setPaintLabels(true);
bSlider.setAlignmentX(Component.LEFT_ALIGNMENT);
SliderListener listener
= new SliderListener();
rSlider.addChangeListener(listener);
gSlider.addChangeListener(listener);
bSlider.addChangeListener(listener);
rLabel = new
JLabel("Red: 0");
rLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
gLabel = new
JLabel("Green: 0");
gLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
bLabel = new
JLabel("Blue: 0");
bLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
controls = new
JPanel();
BoxLayout layout = new
BoxLayout(controls, BoxLayout.Y_AXIS);
controls.setLayout(layout);
controls.add(rLabel);
controls.add(rSlider);
controls.add(Box.createRigidArea(new Dimension(0, 20)));
controls.add(gLabel);
controls.add(gSlider);
controls.add(Box.createRigidArea(new Dimension(0, 20)));
controls.add(bLabel);
controls.add(bSlider);
JPanel colorPanelFrame =
new JPanel();
colorPanelFrame.setLayout(new BoxLayout(colorPanelFrame,
BoxLayout.Y_AXIS));
colorPanel = new
JPanel();
colorPanel.setPreferredSize(new Dimension(100, 100));
colorPanel.setBackground(new Color(0, 0, 0));
colorPanelFrame.add(Box.createVerticalGlue());
colorPanelFrame.add(colorPanel);
colorPanelFrame.add(Box.createVerticalGlue());
add(controls);
add(colorPanelFrame);
}
// Represents the listener for all three
sliders.
private class SliderListener implements
ChangeListener {
private int red, green, blue;
// Gets the value of
each slider, then updates the labels and
// the color
panel.
public void
stateChanged(ChangeEvent event) {
red = rSlider.getValue();
green = gSlider.getValue();
blue = bSlider.getValue();
rLabel.setText("Red: " + red);
gLabel.setText("Green: " + green);
bLabel.setText("Blue: " + blue);
colorPanel.setBackground(new Color(red, green, blue));
}
}
}
--------------------------------------------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;
public class SlideColor {
public static void main(String[] args) {
JFrame frame = new
JFrame("Slide Colors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SlideColorPanel
mainPanel = new SlideColorPanel();
mainPanel.setLayout(new
BoxLayout(mainPanel, BoxLayout.X_AXIS));
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
-----------------------------------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SpeedControlPanel extends JPanel {
private final int WIDTH = 600;
private final int HEIGHT = 400;
private final int BALL_SIZE = 50;
private Circle bouncingBall; // the object that
moves
private Timer timer;
private int moveX, moveY; // increment to move
each time
private JPanel pSpeeder;
private JSlider sSpeeder;
private JLabel lSpeeder;
// Sets up the panel, including the timer
// for the animation
public SpeedControlPanel() {
timer = new Timer(30,
new ReboundListener());
this.setLayout(new
BorderLayout());
bouncingBall = new
Circle(BALL_SIZE);
moveX = moveY = 5;
// Set up a slider
object here
setPreferredSize(new
Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
lSpeeder = new
JLabel("Timer Delay");
lSpeeder.setAlignmentX(Component.LEFT_ALIGNMENT);
sSpeeder = new
JSlider(JSlider.HORIZONTAL, 0, 200, 30);
sSpeeder.setMajorTickSpacing(40);
sSpeeder.setMinorTickSpacing(10);
sSpeeder.setPaintTicks(true);
sSpeeder.setPaintLabels(true);
sSpeeder.setAlignmentX(Component.LEFT_ALIGNMENT);
sSpeeder.addChangeListener(new SlideListener());
pSpeeder = new
JPanel();
pSpeeder.add(lSpeeder);
pSpeeder.add(sSpeeder);
add(pSpeeder, BorderLayout.SOUTH);
timer.start();
}
// Draw the ball
public void paintComponent(Graphics page)
{
super.paintComponent(page);
bouncingBall.draw(page);
}
// An action listener for the timer
public class ReboundListener implements ActionListener {
// actionPerformed is called by the timer
public void
actionPerformed(ActionEvent action) {
bouncingBall.move(moveX, moveY);
// change direction if ball hits a side
int x = bouncingBall.getX();
int y = bouncingBall.getY();
if (x < 0 || x >= WIDTH - BALL_SIZE) {
moveX = moveX * -1;
}
if (y <= 0 || y >= HEIGHT - BALL_SIZE) {
moveY = moveY * -1;
}
repaint();
}
}
// A change listener for the slider.
private class SlideListener implements ChangeListener {
// Called when the state
of the slider has changed;
// resets the delay on
the timer.
public void
stateChanged(ChangeEvent event) {
timer.setDelay(sSpeeder.getValue());
}
}
}
-------------------------------------------------------------------------------------------------------
import java.awt.*;
import java.util.Random;
public class Circle {
private int x, y;
private int radius;
private Color color;
static Random generator = new Random();
// Creates a random circle
public Circle() {
radius =
Math.abs(generator.nextInt()) % 50 + 25;
color = new
Color(Math.abs(generator.nextInt()) % 16777216);
x =
Math.abs(generator.nextInt()) % 600;
y =
Math.abs(generator.nextInt()) % 400;
}
// Creates a circle of a given size (diameter)
public Circle(int size) {
radius = Math.abs(size /
2);
color = new
Color(Math.abs(generator.nextInt()) % 16777216);
x =
Math.abs(generator.nextInt()) % 600;
y =
Math.abs(generator.nextInt()) % 400;
}
// Draws circle on graphics object given
public void draw(Graphics page) {
page.setColor(color);
page.fillOval(x, y,
radius * 2, radius * 2);
}
public void move(int over, int down) {
x = x + over;
y = y + down;
}
//Return the x coordinate of the circle
corner
public int getX() {
return x;
}
//Return the y coordinate of the circle corner
public int getY() {
return y;
}
}