想请教一下键盘监听的问题
想请教一下键盘监听的问题
比如.我想根据键盘的上下左右方向键来更改我的x,y值..
int x = 10;
int y = 10;
按向左 .x轴减1.向右加1 ..按上下就处理y
恳请大侠们给我思路或简单代码来引导一下.感激不尽 javaSE
[解决办法]
package KeyBordLisener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class KeybordLisener_demo extends JFrame {
/**
* @param args
*/
int x=10;
int y=10;
keyevent ke=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
KeybordLisener_demo ny=new KeybordLisener_demo();
}
public KeybordLisener_demo()
{
this.setSize(200, 400);
this.setVisible(true);
ke=new keyevent();
this.addKeyListener(ke);
}
class keyevent implements KeyListener{
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT){
x--;
System.out.println(x);
System.out.println(y);
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{y--;
System.out.println(x);
System.out.println(y);
}
//System.out.println(e.getKeyChar());
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
[解决办法]
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);
}
}
}