IN JAVA Speed Control Problem:
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. (NOTE: the program is derived
from Listing 8.15 and 8.16 in the text. That program uses an image
rather than a circle. You may have used it in an earlier lab on
animation.) 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. Study the code in SlideColorPanel.java
(Listing 10.16 in the text) to help understand the steps
below.
1. Set up a JSlider object. You need to
? Declare it.
? Instantiate it to be a JSlider that is horizontal with values
ranging from 0 to 200, initially set to 30.
? Set the major tick spacing to 40 and the minor tick spacing to
10.
? 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
? 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.
? 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:
? 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;
? Now use this height to adjust the condition that tests to see if
the ball hits the bottom of the panel.
? Test your program to make sure it is correct.
---
SpeedControlPanel.java
//
******************************************************************
// 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)
{
}
}
}
SpeedControl.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);
}
}
Circle.java
//
****************************************************************
// 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;
}
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
Note: SpeedControl.java file is also modified since that file had some syntax errors in it. Fixed.
// SpeedControlPanel.java
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
// declaring slider and panel
private JSlider slider;
private JPanel panel;
// --------------------------------------------
// 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);
// initializing slider with min value 0, max value 200, current value 30
slider = new JSlider(0, 200, 30);
// setting major and minor tick spacings
slider.setMajorTickSpacing(40);
slider.setMinorTickSpacing(10);
// enabling painting ticks and labels
slider.setPaintTicks(true);
slider.setPaintLabels(true);
// setting alignment
slider.setAlignmentX(JSlider.LEFT);
// adding change listener
slider.addChangeListener(new SlideListener());
// creating a label, initializing panel, adding label and slider to
// panel
JLabel label = new JLabel("Timer Delay", JLabel.LEFT);
panel = new JPanel();
panel.add(label);
panel.add(slider);
// adding panel to the south of frame
add(panel, BorderLayout.SOUTH);
// now starting timer
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) {
// finding slide pane height
int slidePanelHt = panel.getSize().height;
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;
// updated condition
if (y <= 0 || y >= HEIGHT - BALL_SIZE - slidePanelHt)
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) {
// fetching current value of slider and setting timer delay
int value = slider.getValue();
timer.setDelay(value);
}
}
}
//SpeedControl.java
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);
}
}
/*OUTPUT*/
Get Answers For Free
Most questions answered within 1 hours.