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

Sliding-Puzzle Applet

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

Problem

I'm a JavaScript coder trying to teach myself Java using online tutorials and ebooks. I have now created my very first applet but feel it only really goes to show the depth of my unappreciation for Java's capabilities. Please, give me some advice as to how to use Java better so that my future projects can be less effort to make, easier to read, easier to maintain and altogether more smoothly designed, just like Java apps are supposed to be.

How would you have implemented the following applet? What would you have done differently? I really don't know what I'm doing here and wish I did because I get the feeling Java's gonna be great once I'm approaching things more sensibly.

```
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

@SuppressWarnings("serial")
public class SlidePuzz extends Applet implements MouseMotionListener, MouseListener {
int gridDim = 3;
int animal = -1;
int pieceDim = 0;
int a; int b;
int gapX = -1; int gapY = -1;
int moveX = -1; int moveY = -1;
Image[][] pieces = new Image[7][7];
int[][] placement = new int[7][7];

String stage = "grid";
String[] imgUrl = { "7028/6814220663_4813a81531",
"7162/6814220921_acb3aa92ee", "7029/6814221019_41323ace8b" };
String imgUrlFlickr = "http://farm8.staticflickr.com/";

Image img;
MediaTracker tr;

public void init() {
setSize(420, 420);
addMouseMotionListener(this);
addMouseListener(this);
}

public void paint(Graphics g) {
if(stage=="grid") {
g.setColor(Color.lightGray);
g.fillRect(0,0,60gridDim,60gridDim);

g.setColor(Color.white);
g.fillRect(60gridDim,0,(7-gridDim)60,420);
g.fillRect(0,60gridDim,60gridDim,(7-gridDim)*60);

g.setColor(Color.black);

for (int i=1; i=0){
g.setColor(Color.white);
g.fillRect(moveXpieceDim, moveYpieceDim, pieceDim, pieceDim);

b = placement[moveX][moveY]%10;
a = (placement

Solution


  • Use Swing components rather than AWT components.



  • Use ImageIO.read(URL/InputStream) over any method that requires a MediaTracker (easier).



  • A MouseAdapter/MouseMotionAdapter might be a better choice if you only need to override one or two methods.



  • The paint method should be refactored. Each object painted might be a class that knows how to paint itself. The if/else structure would then be much shorter.



Note that most things that people would normally do in applets, can be replaced by JS and the HTML5 canvas. Java really comes into its own as free-floating desktop apps.
Edit

The Java Plug-In required to launch applets in browsers was deprecated and removed from Java 9. These points are also relevant to working with a desktop application (in a JFrame).

Context

StackExchange Code Review Q#8712, answer score: 2

Revisions (0)

No revisions yet.