当前位置: 代码迷 >> Eclipse >> Java(myeclipse)怎样获取下上左右的键值
  详细解决方案

Java(myeclipse)怎样获取下上左右的键值

热度:20   发布时间:2016-04-23 12:23:23.0
Java(myeclipse)怎样获取上下左右的键值
我是想在控制台作一个累死于炫舞的以输入上下左右键的东东,求大神指示. 鄙人衷心感谢

------解决方案--------------------
用GUI程序是很容易的:

定义一个类,继承JFrame,然后重写其processKeyEvent函数,类似于:
Java code
import java.awt.event.*;import javax.swing.*;public class KeyProcess extends JFrame {    public KeyProcess(){        this.setDefaultCloseOperation(EXIT_ON_CLOSE);        this.setSize(800, 600);    }    public void processKeyEvent(KeyEvent e) {        System.out.println(e);    }    public static void main(String[] args) {        KeyProcess wnd = new KeyProcess();        wnd.setVisible(true);    }}
------解决方案--------------------
implements KeyListener试试。。。复写public void keyPressed(KeyEvent e) {}这个方法- -不过我好像是在swing界面上弄的,控制台不知道可不可以。。。我没时间了-。-培训去。。。
------解决方案--------------------
Java code
[code=Java]public class OtherTest extends JFrame {    private static final long serialVersionUID = 1L;    public static void main(String[] args) {        MyPanel mp = new MyPanel();        OtherTest ot = new OtherTest();        ot.add(mp);        ot.addKeyListener(mp);         ot.setSize(400, 300);        ot.setTitle("Moving XO");        ot.setLocationRelativeTo(null);        ot.setVisible(true);    }}class MyPanel extends JPanel implements KeyListener {    private static final long serialVersionUID = 1L;    int x = 10;    int y = 10;    public void paint(Graphics g) {        super.paint(g);        g.fillOval(x, y, 10, 10);    }    public void keyPressed(KeyEvent e) {        if (e.getKeyCode() == KeyEvent.VK_DOWN) {            y++;        } else if (e.getKeyCode() == KeyEvent.VK_UP) {            y--;        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {            x--;        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {            x++;        }        this.repaint();    }    public void keyTyped(KeyEvent e) {        // TODO Auto-generated method stub            }    public void keyReleased(KeyEvent e) {        // TODO Auto-generated method stub            }    }
  相关解决方案