Java Code

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class SlidingPuzzle extends JApplet
	implements ActionListener
{
	Image image;
	ImageIcon icon;
	JButton buttons[ ], blankButton;
	JPanel grid;
	JPanel spots[];
	int currentBlankSpot;
	public void init( )
	{
		setSize( 500,600);
		setLayout( new FlowLayout() );
		buttons = new JButton[16];
		grid = new JPanel( new GridLayout(4,4) );
		setupPanels( );
		setupImage( );
		grid.setSize(400,400);
		add(grid);
	}
	public void setupPanels( )
	{
		spots = new JPanel[16];
		blankButton = new JButton( " ");
		blankButton.setBackground( Color.BLACK );
		for( int i=0; i<spots.length; i++ )
		{
			spots[i] = new JPanel( new BorderLayout( ));
			grid.add(spots[i]);
		}
	}
	public void setupImage( )
	{
		image = getImage(getCodeBase(), "SouthAfricaMasks.jpg");
		MediaTracker tracker = new MediaTracker(this);
		tracker.addImage(image,1);
		try{ tracker.waitForAll();
		} catch(Exception e) { }
		BufferedImage bimage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_ARGB);
		Graphics g = bimage.getGraphics( );
		g.drawImage(image,0,0,this);

		int width=image.getWidth(this);
		int height=image.getHeight(this);
		System.out.println( width + " h = " + height );
		int count = 0;
		for( int i=0; i<4; i++ )
		  for( int j=0; j<4; j++ )	// don't display the last one, this is the blank spot
		{
			BufferedImage window = bimage.getSubimage(i*width/4,j*height/4,width/4,height/4);
			setupButton( count++, window );
		}
		// override the last button with the blank spot
		spots[spots.length-1].add(blankButton);
		currentBlankSpot = spots.length-1;
	}
	public void setupButton( int id, Image img )
	{
		buttons[id] = new JButton( new ImageIcon(img) );
		buttons[id].addActionListener(this);
		buttons[id].setMargin(new Insets(0,0,0,0) );
		buttons[id].setContentAreaFilled(false);
		spots[id].add(buttons[id],BorderLayout.CENTER);
	}
	public void actionPerformed(ActionEvent ae )
	{
		Object src = ae.getSource();
		for( int i=0; i<buttons.length; i++ )
		{
			if( buttons[i] == src )
			{
				if( currentBlankSpot - 1 == i || currentBlankSpot - 4 == i 
					|| currentBlankSpot + 1 == i || currentBlankSpot + 4 == i )
					{
						// exchange spots with blank
						spots[currentBlankSpot].removeAll();
						spots[i].removeAll();

						spots[currentBlankSpot].add(buttons[i]);
						spots[i].add(blankButton);

						buttons[currentBlankSpot] = buttons[i];
						buttons[i] = blankButton;
						currentBlankSpot = i;
						repaint();
						return;	// must have this here
					}
			}
		}
	}
}

©2006 by E.S.Boese. All Rights Reserved