import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SlidingPuzzle extends JFrame implements MouseListener
{
public static void main(String[] args){
SlidingPuzzle frame=new SlidingPuzzle();
frame.TestPanel();
frame.setTitle("Numeric Sliding Puzzle");
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void TestPanel(){
Container container=getContentPane();
container.setLayout(new GridLayout(3,3,5,5));
PuzzleTile[] listenerPanel;
listenerPanel=new PuzzleTile[9];
int[] myList=new int[9];
outer:
for(int i=0;i<=8;i++){
int j=(int)(Math.random()*9);
myList[i]=j;
if(null == listenerPanel[j]){
listenerPanel[j] = new PuzzleTile(j);
}
if(i==0)
{
container.add(listenerPanel[j]);
listenerPanel[j].addMouseListener(this);
}
else{
for(int k=0;k<i;){
if(myList[k]==myList[i]){
i--;
continue outer;
}
k++;
if(k==i)
{
container.add(listenerPanel[j]);
listenerPanel[j].addMouseListener(this);
}
}
}
}
}
public void mousePressed(MouseEvent e){
PuzzleTile pt = (PuzzleTile) e.getSource();
if (pt.getBackground().equals(Color.white)) {
return;
}
pt.setBackground(Color.LIGHT_GRAY);
}
public void mouseReleased(MouseEvent e){
PuzzleTile pt = (PuzzleTile) e.getSource();
if (pt.getBackground().equals(Color.white)) {
return;
}
pt.setBackground(Color.DARK_GRAY);
}
public void mouseClicked(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
}
public class PuzzleTile extends JPanel {
private String tileNumber;
public PuzzleTile(int number) {
super();
if (number == 0) {
this.setBackground(Color.white);
}
else {
this.setBackground(Color.darkGray);
}
this.tileNumber = "" + number;
}
public void paintComponent(Graphics graphics) {
Font a=new Font("Arial",Font.BOLD,30);
graphics.setFont(a);
graphics.setColor(Color.white);
super.paintComponent(graphics);
FontMetrics b=graphics.getFontMetrics(a); |
|