键盘监听
采用接口方式,使用键盘的方向键来移动图片;同时当按住A时(英文状态下),可以展示拼图的原图;按下W键,可以一键完成拼图。
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
//上38;下40;左37;右39
//测试
//System.out.println(code);
if(code == 39){
if(y == 3) return;
result[x][y] = result[x][y + 1];
result[x][y + 1] = 0;
y ++;
initImage();
System.out.println("向右移动");
} else if (code == 40) {
if(x == 3) return;
result[x][y] = result[x + 1][y];
result[x + 1][y] = 0;
x ++;
initImage();
System.out.println("向下移动");
}else if(code == 37){
if(y == 0) return;
result[x][y] = result[x][y - 1];
result[x][y - 1] = 0;
y --;
initImage();
System.out.println("向左移动");
}else if(code == 38){
if(x == 0) return;
result[x][y] = result[x - 1][y];
result[x - 1][y] = 0;
x --;
initImage();
System.out.println("向上移动");
} else if (code == 65) {
initImage();
} else if (code == 87) {
//按键W
int[] tempArr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0};
for (int i = 0; i < tempArr.length; i++) {
result[i / 4][i % 4] = tempArr[i];
}
initImage();
}
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == 65) {//按键A
//把界面中所有的图片删除
this.getContentPane().removeAll();
//加载完整图片和背景图片
JLabel all = new JLabel(new ImageIcon(path + "all.jpg"));
all.setBounds(83, 134, 420, 420);
this.getContentPane().add(all);
//添加背景图片
JLabel background = new JLabel(new ImageIcon("D:\\JAVA\\JAVA\\study\\image\\background.png"));
background.setBounds(40, 40, 508, 560);
this.getContentPane().add(background);
this.getContentPane().repaint();
}
}