Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask Java Expert


Home >> Java

Simulates a bouncing ball. Extend to allow mulitple balls. You can use the +I or -I button to increase or decrease the number of the balls and use teh Suspend and Resume buttoms to freeze the balls or resume bouncing. For each ball, assign a random color.

I am having trouble getting my program to run. Here is what I came up with:

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.border.LineBorder;

public class BouncingBalls extends JApplet {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JApplet applet = new BouncingBalls();

frame.add(applet);

frame.setTitle("BouncingBalls");

frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(3);

frame.setSize(400,200);
frame.setVisible(true);
}
public BouncingBalls()
{

add(new BallControl());
}
class BallControl extends JPanel implements ActionListener, AdjustmentListener
{
private Ball ball;
private JButton jbtSuspend;
private JButton jbtResume;
private JButton jbtAdd;
private JButton jbtSubtract;
private JScrollBar jsbDelay;

public BallControl()
{
ball = new Ball();

jbtSuspend = new JButton("Suspend");

jbtResume = new JButton("Resume");

jbtAdd = new JButton("+1");


jbtSubtract = new JButton("-1");
jsbDelay = new JScrollBar();
JPanel panel = new JPanel();

panel.add(jbtSuspend);

panel.add(jbtResume);

panel.add(jbtAdd);

panel.add(jbtSubtract);

ball.setBorder(new LineBorder(Color.red));
jsbDelay.setOrientation(0);
ball.setDelay(jsbDelay.getMaximum());
setLayout(new BorderLayout());
add(jsbDelay, "North");
add(ball, "Center");
add(panel, "South");
jbtSuspend.addActionListener(this);
jbtResume.addActionListener(this);
jbtAdd.addActionListener(this);
jbtSubtract.addActionListener(this);
jsbDelay.addAdjustmentListener(this);
}


class Ball extends JPanel implements Runnable
{

class BallState
{
int x;

int y;
int dx;
int dy;
Color color;

public BallState()
{
x = 0;
y = 0;
dx = 2;
dy = 2;

int r = (int)(Math.random() * 1000) % 256;
int g = (int)(Math.random() * 1000) % 256;
int b = (int)(Math.random() * 1000) % 256;

color = new Color(r,g,b);
}
}
public void add()
{
list.add(new BallState());
}
public void subtract()
{
if(list.size() > 0)
list.remove(list.size() - 1);
}
protected void paintComponent (Graphics g)
{
super.paintComponent(g);

for(int i = 0; i < list.size(); i++);
{
BallState ball;
ball = (BallState)list.get(i);
if(ball.x < radius) ball.dx = Math.abs(ball.dx);
if(ball.x > getWidth() - radius) ball.dx = -Math.abs(ball.dx);
if(ball.y < radius) ball.dy = Math.abs(ball.dy);
if(ball.y > getHeight() - radius) ball.dy = -Math.abs(ball.dy);

ball.x += ball.dx;
ball.y += ball.dy;
g.setColor(ball.color);
g.fillOval(ball.x - radius, ball.y - radius, radius*2, radius*2);
}
}
public void run()
{
try
{
while(true)
{
while(!isSuspended)
{
repaint();
Thread.sleep(speed);
}
lock.lock();
suspended.await();
lock.unlock();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

public void resume()
{
lock.lock();
isSuspended = false;
suspended.signalAll();
lock.unlock();
}
public void suspend()
{
lock.lock();
isSuspended = true;
lock.unlock();
}

public void setDelay(int ms)
{
speed = ms;
}
private int speed;
protected Thread timer;
private ArrayList list;
private int x;
private int y;
private int radius ;
private int dx;
private int dy;
boolean isSuspended;
Lock lock;
Condition suspended;

public Ball()
{
speed = 10;
timer = new Thread(this);
list = new ArrayList();
x = 0;
y = 0;
radius = 5;
dx = 2;
dy = 2;
isSuspended = false;
lock = new ReentrantLock();
suspended = lock.newCondition();
timer.start();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbtSuspend) ball.suspend();
else
if(e.getSource() == jbtResume) ball.resume();
else
if(e.getSource() == jbtAdd) ball.add();
else

if(e.getSource() == jbtSubtract) ball.subtract();
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
ball.setDelay(jsbDelay.getMaximum() - e.getValue());
}
}

}

 

 

Java, Programming

  • Category:- Java
  • Reference No.:- M9457977

Have any Question?


Related Questions in Java

Assessment database and multithread programmingtasktask 1

Assessment: Database and Multithread Programming Task Task 1: Grade Processing University grading system maintains a database called "GradeProcessing" that contains number of tables to store, retrieve and manipulate stud ...

Answer the following question whats the difference public

Answer the following Question : What's the difference public inheritance and private inheritance? What can derived classes inherit from base classes? What cannot be inherited from base classes?

Assignment - method in our madnessthe emphasis for this

Assignment - "Method in our Madness" The emphasis for this assignment is methods with parameters. In preparation for this assignment, create a folder called Assign_3 for the DrJava projects for the assignment. A Cityscap ...

Chatbotscreate a small networked chat application that is

Chatbots Create a small, networked chat application that is populated by bots. Introduction On an old server park, filled with applications from the early days of the internet, a few servers still run one of the earliest ...

Overviewyou are required to use java se 80 and javafx to

Overview You are required to use Java SE 8.0 and JavaFX to develop a Graphical User Interface (GUI) for the FlexiRent rental property management program created in Assignment 1. This assignment is designed to help you: 1 ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

Overviewyou are required to use java se 80 and javafx to

Overview You are required to use Java SE 8.0 and JavaFX to develop a Graphical User Interface (GUI) for the FlexiRent rental property management program created in Assignment 1. This assignment is designed to help you: 1 ...

Operating systems assignment -problem 1 sharing the bridgea

Operating Systems Assignment - Problem 1: Sharing the Bridge A new single lane bridge is constructed to connect the North Island of New Zealand to the South Island of New Zealand. Farmers from each island use the bridge ...

Project requirementsfor the problem described in the next

Project requirements For the problem described in the next section, you must do the following: 1. include your student ID at the end of all filenames for all java code files. Three classes have been identified in section ...

Can someone please help me with the following java

can someone please help me with the following java question The input is an N by N matrix of nonnegative integers. Each individual row is a decreasing sequence from left to right. Each individual column is a decreasing s ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As