File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Why doesn't this work? The 15-puzzle using swing. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Why doesn Watch "Why doesn New topic

Why doesn't this work? The 15-puzzle using swing.

Bhuturam Pandey

Joined: Feb 27, 2004
Posts: 1
Hi Friends,
I wrote this program to do the 15 Puzzle using swing. It compiles properly and the display comes up okay. But the blank button and the numbered buttons are supposed to swap on click if they are neighbours (north, south,eat or west). That's not happening. And I have no idea why. Can you guys help me?
Also, how do I get the frame displayed at teh centre of the screen?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PuzzleFrame extends JFrame implements ActionListener {
private Container gframe;
private JButton[] ButtArray = new JButton[16];
public PuzzleFrame() {
gframe = this.getContentPane();
gframe.setLayout(new GridLayout(4,4));
for(int i = 0;i < 15;i++) {
ButtArray[i] = new JButton(""+(1+i));
ButtArray[15] = new JButton("");
public int north(int i) {
if ((i<4)&&(i>=0)) return -1;
else return (i-4);
public int south(int i) {
if ((i>11)&&(i<16)) return -1;
else return (i+4);
public int west(int i) {
if ((i==0)||(i==4)||(i==8)||(i==12)) return -1;
else return (i-1);
public int east (int i) {
if ((i==3)||(i==7)||(i==11)||(i==15)) return -1;
else return (i+1);
public void astionPerformed(ActionEvent click) {
Object source = click.getSource();
for(int i = 0; i<16;i++) {
if (source == ButtArray[i]) {
if (north(i) != (-1)) {
if ButtArray[north(i)].getText().equals("")) {
else if (south(i) != (-1)) {
if ButtArray[south(i)].getText().equals("")) {
else if (east(i) != (-1)) {
if ButtArray[east(i)].getText().equals("")) {
else if (west(i) != (-1)) {
if ButtArray[west(i)].getText().equals("")) {
public static void main(String[] args) {
PuzzleFrame pfr = new PuzzleFrame();
Carlos Failde
Ranch Hand

Joined: Oct 20, 2000
Posts: 84
I think your problem is in actionPerformed() where you check for squares in all directions and only when there is a square found do you check if that square is the blank square. Consider the situation where there is a square north and when it is checked is found to be nonblank - does your code as it now stands then go on to check the squares south, east, and west? The answer is no. You want to change that.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24187

Moving to the Swing/AWT forum.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Why doesn't this work? The 15-puzzle using swing.