import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
class JButtonGame extends JFrame implements ActionListener {
private int nRows,nCols,nButtons;
private int blankCol,blankRow,clickedRow,clickedCol;
private JButton[][] buttons;
private JTextField textField;
public JButtonGame(){
setSize(200,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent event){
System.exit(0);
}
});
JPanel panel=new JPanel();
nRows=4;nCols=4;nButtons=nRows*nCols;
panel.setLayout(new GridLayout(nRows,nCols));
buttons=new JButton[nRows][nCols];
for(int nRow=0;nRow<nRows;nRow++){
for(int nCol = 0;nCol<nCols;nCol++){
buttons[nRow][nCol]=new JButton("");
buttons[nRow][nCol].addActionListener(this);
panel.add(buttons[nRow][nCol]);
}
}
getContentPane().add("Center",panel);
textField = new JTextField("",80);
textField.setEditable(false);
getContentPane().add("South",textField);
int labelsUsed[]=new int [nButtons];
for(int i=0;i<nButtons;i++){
boolean labelUsed;int label;
do{
label = random(nButtons)+1;
labelUsed = false;
for(int j=0;j<i;j++){
labelUsed = ((labelUsed) || (label == labelsUsed[j]));
}
}while(labelUsed);
labelsUsed[i]=label;
int nRow= i/nCols;int nCol=i-nRow*nCols;
buttons[nRow][nCol].setText((new Integer(label)).toString());
}
getButtonPosition((new Integer(nButtons)).toString());
blankRow = clickedRow;blankCol = clickedCol;
JButton blank = buttons[clickedRow][clickedCol];
blank.setText("");
blank.setBackground(Color.green);
}//end constructionJButtonGame()
private int random(int k){
return (int)(k*Math.random()-0.1);
}
private void getButtonPosition(String label){
for(int nr=0;nr<nRows;nr++){
for(int nc=0;nc<nCols;nc++){
if(buttons[nr][nc].getText().equals(label)){
clickedRow =nr;
clickedCol=nc;
textField.setText("["+nr+","+nc+"]"+label);
}
}
}
}//end method getButtonPosition(String)
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
getButtonPosition(e.getActionCommand());
textField.setText("["+blankRow+","+blankCol+"]=>["+clickedRow+","+clickedCol+"]");
if(clickedRow==blankRow){
if(Math.abs(clickedCol-blankCol)==1){
moveBlank(blankRow,blankCol,clickedRow,clickedCol);
}else if(clickedCol==blankCol){
if(Math.abs(clickedRow-blankRow)==1){
moveBlank(blankRow,blankCol,clickedRow,clickedCol);
}
}
}
}//end method actionPerformed
public void moveBlank(int oldRow,int oldCol,int newRow,int newCol){
JButton oldBlank = buttons[oldRow][oldCol];
JButton newBlank = buttons[newRow][newCol];
String label = newBlank.getText();
newBlank.setText("");
newBlank.setBackground(Color.green);
oldBlank.setText(label);
oldBlank.setBackground(Color.lightGray);
blankRow = newRow;blankCol=newCol;
}//end method moveBlank
public static void main(String[] args){
new JButtonGame().setVisible(true);
}//end method main
}