1. 程式人生 > >編寫程式,實現使用鍵盤上的上下左右箭頭控制介面上圖片的移動。

編寫程式,實現使用鍵盤上的上下左右箭頭控制介面上圖片的移動。


//MyFrame.java

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class MyFrame extends JFrame implements KeyListener {


private Icon icon,icon2;
private JLabel lab;


public MyFrame(String s) {
super(s);
setSize(700, 500);
setLocationRelativeTo(null);


JPanel contentPane = new JPanel(null);
// contentPane.setLayout();
setContentPane(contentPane);


icon = new ImageIcon("D:\\圖片\\c.gif");
lab = new JLabel(icon);
lab.setBounds(0, 0, 100, 100);
addKeyListener(this);


contentPane.add(lab);


setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub


}


@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
icon2 = new ImageIcon("D:\\圖片\\d.gif");
lab.setIcon(icon2);
}


@Override
public void keyReleased(KeyEvent e) {

lab.setIcon(icon);
// TODO Auto-generated method stub
int x = lab.getX();
int y = lab.getY();
if (x >= 700) {
lab.setBounds(0, y, 100, 100);
} else if (x < 0) {
lab.setBounds(700, y, 100, 100);
} else if (y < 0) {
lab.setBounds(x, 500, 100, 100);
} else if (y > 500) {
lab.setBounds(x, 0, 100, 100);
} else {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
lab.setBounds(x - 50, y, 100, 100);
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
lab.setBounds(x + 50, y, 100, 100);
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
lab.setBounds(x, y - 50, 100, 100);
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
lab.setBounds(x, y + 50, 100, 100);
}
}
}

}

//MyFrameDemo.java

public class MyFrameDemo {
public static void main(String[] args) {
MyFrame mf = new MyFrame("鍵盤事件演示");
}
}