Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
bouncing-ball/BouncingBall.java
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
78 lines (75 sloc)
2.29 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Lab 2: BouncingBall.java | |
* Extends SmartEllipse, adding the ability to "bounce." | |
*/ | |
public class BouncingBall extends SmartEllipse implements Mover { | |
private int _changeX, _changeY; // attributes | |
private int _moveLen = 5; | |
private javax.swing.JPanel _panel; // peer object (and container) | |
private javax.swing.Timer _timer; | |
public BouncingBall (java.awt.Color aColor, int anInterval, | |
javax.swing.JPanel aPanel){ | |
// Instantiate the JPanel | |
super(aColor); | |
// Initialize the change in each direction per timer tick | |
_changeX = _moveLen; | |
_changeY = _moveLen; | |
// Save the peer which is the panel on which the block appears | |
_panel = aPanel; | |
// Instantiate the timer for the block | |
_timer = new MoveTimer(anInterval, this); | |
// Start the timer | |
_timer.start(); | |
} | |
public void move() { | |
int nextX = (int)this.getX() + _changeX; | |
int nextY = (int)this.getY() + _changeY; | |
if (nextX <= this.getMinBoundX()) { | |
_changeX *= -1; | |
nextX = this.getMinBoundX(); | |
} | |
else if (nextX >= this.getMaxBoundX()) { | |
_changeX *= -1; | |
nextX = this.getMaxBoundX(); | |
} | |
if (nextY <= this.getMinBoundY()) { | |
_changeY *= -1; | |
nextY = this.getMinBoundY(); | |
} | |
else if (nextY > this.getMaxBoundY()){ | |
_changeY *= -1; | |
nextY = this.getMaxBoundY(); | |
} | |
this.setLocation(nextX, nextY); | |
_panel.repaint(); | |
} | |
public int getMinBoundX() { | |
return (int) _panel.getX(); | |
} | |
public int getMinBoundY() { | |
return (int) _panel.getY(); | |
} | |
public int getMaxBoundX() { | |
return (int) (_panel.getX() + _panel.getWidth() - this.getWidth()); | |
} | |
public int getMaxBoundY() { | |
return (int) (_panel.getY() + _panel.getHeight() | |
- this.getHeight()); | |
} | |
public void setMoveLength(int value) | |
{ | |
_moveLen = value; | |
if(_changeX >=0) | |
_changeX = value; | |
else | |
_changeX = value * -1; | |
if(_changeY >=0) | |
_changeY = value; | |
else | |
_changeY = value * -1; | |
} | |
public java.awt.Color getColor() | |
{ | |
return super.getFillColor(); | |
} | |
} |