HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java Bouncing Ball Review

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ballbouncingreviewjava

Problem

Just looking for some help reviewing/refactoring. For example, could the classes random/vertical be refactored into 1 class instead of 2?

BouncingBalls.java

`import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BouncingBalls extends JPanel implements MouseListener {

protected List randomBalls = new ArrayList(20);
protected List verticalBalls = new ArrayList(20);
private Container container;
private DrawCanvas canvas;
private Boolean doubleClick = false;
private final Integer waitTime = (Integer) Toolkit.getDefaultToolkit()
.getDesktopProperty("awt.multiClickInterval");
private static int canvasWidth = 500;
private static int canvasHeight = 500;
public static final int UPDATE_RATE = 30;
int count = 0;

public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}

public BouncingBalls(int width, int height) {
canvasWidth = width;
canvasHeight = height;

container = new Container();

canvas = new DrawCanvas();
this.setLayout(new BorderLayout());
this.add(canvas, BorderLayout.CENTER);
this.addMouseListener(this);

start();

}

public void start() {

Thread t = new Thread() {

public void run() {

while (true) {

update();
repaint();
try {
Thread.sleep(1000 / UPDATE_RATE);
} catch (InterruptedException e) {
}
}
}
};
t.start();
}

public void upda

Solution

Your VerticalBall class and RandomBall have lots of duplicate code(should it?). So you can make an abstract Ball class and define the duplicate codes there. This way you can have a clear hierarchy of classes.

See : re-factoring also.

BTW in Java final variable names are written like CAPITAL_WITH_UNDERSCORES.

Context

StackExchange Code Review Q#31687, answer score: 2

Revisions (0)

No revisions yet.