Question

IN JAVA Speed Control Problem: The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated...

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;
}
}

Homework Answers

Answer #1

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*/

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
When I wrote this code in the Eclipse program, I did not see a output .....
When I wrote this code in the Eclipse program, I did not see a output .. Why? ___________________ public class YClass { private int a; private int b; public void one(){ } public void two ( int x , int y ) ; a=x; b=y; } public YClass() { a=0; b=0; } } class XClass extends YClass{ private int z; public void one() { } public XClass { z=0; } } YClass Object; XClass Object;
Hello. I have an assignment that is completed minus one thing, I can't get the resize...
Hello. I have an assignment that is completed minus one thing, I can't get the resize method in Circle class to actually resize the circle in my TestCircle claass. Can someone look and fix it? I would appreciate it! If you dont mind leaving acomment either in the answer or just // in the code on what I'm doing wrong to cause it to not work. That's all I've got. Just a simple revision and edit to make the resize...
Compile and execute the application. You will discover that is has a bug in it -...
Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn. Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code. Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the computer through a user interface. The user will choose to throw Rock, Paper or Scissors and the computer will randomly select between the two. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should then reveal the computer's choice and print a statement indicating if the user won, the computer won, or if it was a tie. Allow...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....
What is the output of the following Java program? public class Food {     static int...
What is the output of the following Java program? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { s = flavor; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         pepper.setFlavor("spicy");         System.out.println(pepper.getFlavor());     } } Select one: a. sweet b. 1 c. The program does not compile. d. 2 e. spicy...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it takes multiple sets of hours, minutes and seconds from the user in hh:mm:ss format and then computes the total time elapsed in hours, minutes and seconds. This can be done using the Time object already given to you. Tasks: Complete addTimeUnit() in AddTime so that it processes a string input in hh:mm:ss format and adds a new Time unit to the ArrayList member variable....
Covert the following Java program to a Python program: import java.util.Scanner; /** * Displays the average...
Covert the following Java program to a Python program: import java.util.Scanner; /** * Displays the average of a set of numbers */ public class AverageValue { public static void main(String[] args) { final int SENTINEL = 0; int newValue; int numValues = 0;                         int sumOfValues = 0; double avg; Scanner input = new Scanner(System.in); /* Get a set of numbers from user */ System.out.println("Calculate Average Program"); System.out.print("Enter a value (" + SENTINEL + " to quit): "); newValue =...
Whenever I try to run this program a window appears with Class not Found in Main...
Whenever I try to run this program a window appears with Class not Found in Main project. Thanks in Advance. * * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Assignment10; /** * * @author goodf */ public class Assignment10{ public class SimpleGeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated;    /**...