Add a keylistener to the button (working with KeyBindings would be better).
Make two int variables for the indices of the current panel (e.g. x,y).
In the keyPressed(KeyEvent e) method
remove the button from the current panel and add it to the new panel.
Note: The button must have focus, if you want to move it with the keys.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame extends JFrame {
private JPanel [][] innerCells;
private JButton b = new JButton("G");
private int x=0;
private int y=0;
private final int size=10;
public MyFrame() {
JFrame fr = new JFrame("Final Exams");
fr.setSize(800, 600);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);
fr.setLocationRelativeTo(null);
JPanel p = new JPanel(new GridLayout(size, size));
innerCells = new JPanel[size][size];
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
innerCells[i][j] = new JPanel();
innerCells[i][j].setBorder(BorderFactory.createLineBorder(Color.orange));
p.add(innerCells[i][j]);
}
}
innerCells[0][0].add(b);
fr.add(p);
b.addKeyListener(new KListener());
}
private class KListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
innerCells[x][y].remove(b);
innerCells[x][y].repaint();
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
x= x-1;
break;
case KeyEvent.VK_DOWN:
x= (x+1)%size;
break;
case KeyEvent.VK_LEFT:
y= y-1;
break;
case KeyEvent.VK_RIGHT :
y= (y+1)%size;
break;
}
if(x<0) x=size-1;
if(y<0)y=size-1;
innerCells[x][y].add(b);
innerCells[x][y].revalidate();
b.requestFocus();
}
´ }
public static void main(String[] args){
MyFrame f = new MyFrame();
}
}