日期:2014-05-20 浏览次数:20694 次
import javax.swing.*; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; public class KeyListenerFrame extends JFrame implements KeyListener { private JTextArea jta=new JTextArea(10,10); public KeyListenerFrame(String title){ super(title); jta.addKeyListener(this); this.getContentPane().add(jta); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); } public static void main(String[] args) { new KeyListenerFrame("demo"); } @Override public void keyTyped(KeyEvent e) { //To change body of implemented methods use File | Settings | File Templates. // if(e.getKeyCode()==KeyEvent.VK_DOWN){ // jta.append("↓"); // } } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_DOWN: jta.append("↓"); break; case KeyEvent.VK_UP: jta.append("↑"); break; case KeyEvent.VK_LEFT: jta.append("←"); break; case KeyEvent.VK_RIGHT: jta.append("→"); break; // default: // jta.append(""+e.getKeyChar()); } } @Override public void keyReleased(KeyEvent e) { //To change body of implemented methods use File | Settings | File Templates. } }
------解决方案--------------------
这里给你贴一个具体的实例,但是还有点小问题就是 左箭头的具体实现要再用程序控制光标
import javax.swing.*; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; public class KeyListenerFrame extends JFrame implements KeyListener { private JTextArea jta=new JTextArea(10,10); public KeyListenerFrame(String title){ super(title); jta.addKeyListener(this); this.getContentPane().add(jta); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); } public static void main(String[] args) { new KeyListenerFrame("demo"); } @Override public void keyTyped(KeyEvent e) { //To change body of implemented methods use File | Settings | File Templates. // if(e.getKeyCode()==KeyEvent.VK_DOWN){ // jta.append("↓"); // } } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_DOWN: jta.append("↓"); break; case KeyEvent.VK_UP: jta.append("↑"); break; case KeyEvent.VK_LEFT: jta.append("←"); break; case KeyEvent.VK_RIGHT: jta.append("→"); break; // default: // jta.append(""+e.getKeyChar()); } } @Override public void keyReleased(KeyEvent e) { //To change body of implemented methods use File | Settings | File Templates. } }