日期:2014-05-20 浏览次数:20782 次
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FrameTest
{
JFrame mainFrame = new JFrame("KeyListener");
JLabel label = new JLabel();
int x = 10;
int y = 10;
public FrameTest()
{
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400, 400);
label.setText(getStr(x, y));
mainFrame.add(label);
mainFrame.setVisible(true);
mainFrame.addKeyListener(new keylist());
}
//在标签上显示x,y的格式;
public String getStr(int x, int y)
{
String s = "x = " + x + ", y = " + y;
return s;
}
public static void main(String[] args)
{
new FrameTest();
}
//实现按键监听;
private class keylist extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
switch (key)
{
// JDK对四个方向的常量定义;
// public static final int VK_LEFT = 0x25;
// public static final int VK_UP = 0x26;
// public static final int VK_RIGHT = 0x27;
// public static final int VK_DOWN = 0x28;
case 37:
x--;
break;// VK_LEFT
case 39:
x++;
break;
case 38:
y++;
break;
case 40:
y--;
break;
}
label.setText(getStr(x, y));
mainFrame.add(label);
mainFrame.setVisible(true);
}
}
}