Question

In: Computer Science

The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated panel) with a circle that...

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

Solutions

Expert Solution

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


Related Solutions

(Display a Circle and Its Attributes) Write a program that displays a circle of random size...
(Display a Circle and Its Attributes) Write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumference. Use the following equations: diameter = 2 × radius, area = π × radius2, circumference = 2 × π × radius. Use the constant Math.PI for pi (π). All drawing should be done on a subclass of JPanel, and the results of the calculations should be displayed in a read-only JTextArea.
The files provided in the code editor to the right contain syntax and/or logic errors. In...
The files provided in the code editor to the right contain syntax and/or logic errors. In each case, determine and fix the problem, remove all syntax and coding errors, and run the program to ensure it works properly. DebugBox.java public class DebugBox { private int width; private int length; private int height; public DebugBox() { length = 1; width = 1; height = 1; } public DebugBox(int width, int length, height) { width = width; length = length; height =...
The files provided in the code editor to the right contain syntax and/or logic errors. In...
The files provided in the code editor to the right contain syntax and/or logic errors. In each case, determine and fix the problem, remove all syntax and coding errors, and run the program to ensure it works properly. Please Fix code and make Copy/Paste avaliable // Application allows user to enter a series of words // and displays them in reverse order import java.util.*; public class DebugEight4 {    public static void main(String[] args)    {       Scanner input = new Scanner(System.in);       int...
Edit question Write a program that merges two files as follows. The two files are in...
Edit question Write a program that merges two files as follows. The two files are in the docsharing which you can download it. One file will contain usernames(usernames.txt):foster001smith023nyuyen002...The other file will contain passwords(passwords.txt):x34rdf3ep43e4rddw32eds22...The program should create a third file matching username and passwords(usernamesPasswords.txt):foster001x34rdf3esmith023p43e4rddnyuyen002w32eds22......Give the user of your programs the option of displaying you output file. CAN ANYONE SOLVE THIS IN C
The accompanying 2 files (boynames.txt and girlnames.txt) contain the results of a recent census of boy...
The accompanying 2 files (boynames.txt and girlnames.txt) contain the results of a recent census of boy and girl births in the last year. Each record of the files contain a given name and the number of new born children receiving that name. E.g.,           Matthew 23567          or            Alison 17658 Each name is separated from the number by a blank space. There are also some common names given to both boys and girls, e.g., Riley. They will appear in both the...
Enhancing a Movable Circle File MoveCircle contains a program that uses CirclePanel to draw a circle...
Enhancing a Movable Circle File MoveCircle contains a program that uses CirclePanel to draw a circle and let the user move it by pressing buttons. Save these files to your directory and compile and run MoveCircle to see how it works. Then modify the code in CirclePanel as follows: 1. Add mnemonics to the buttons so that the user can move the circle by pressing the ALT-l, ALT-r, ALT-u, or ALT-d keys. 2. Add tooltips to the buttons that indicate...
These are the questions and all three SPSS files which i uploaded are associated with these...
These are the questions and all three SPSS files which i uploaded are associated with these questions tubercle bacteria In an article to the Norwegian epidemiologist Tor Bjerkedal (1960): "Acquisition of resistance in guinea pigs infected with different doses of virulent tubercle bacilli", American Journal of Hygiene, 72, 130-148, the survival time for guinea pigs injected with tuberculosis bacteria. Data is provided in the data file tubercle_bacilli.sav. Provide a descriptive description of the data, with mean, median, standard deviation and...
Please use C++. You will be provided with two files. The first file (accounts.txt) will contain...
Please use C++. You will be provided with two files. The first file (accounts.txt) will contain account numbers (10 digits) along with the account type (L:Loan and S:Savings) and their current balance. The second file (transactions.txt) will contain transactions on the accounts. It will specifically include the account number, an indication if it is a withdrawal/deposit and an amount. Both files will be pipe delimited (|) and their format will be the following: accounts.txt : File with bank account info...
Write a program that uses an array for time and temperature. The program should contain an...
Write a program that uses an array for time and temperature. The program should contain an array with 24 elements, each of which is holding a temperature for a single hour. Your program should have a function that lists all of the temperatures that are held in the array. Temperatures should be listed to console with one entry per line. Your program should have a function that lists a single temperature entry. You should ask the user for a number...
C++ Goals: Write a program that works with binary files. Write a program that writes and...
C++ Goals: Write a program that works with binary files. Write a program that writes and reads arrays to and from binary files. Gain further experience with functions. Array/File Functions Write a function named arrayToFile. The function should accept three arguments: the name of file, a pointer to an int array, and the size of the array. The function should open the specified file in binary made, write the contents into the array, and then close the file. write another...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT