- Java code
package ch4;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import javax.swing.JFrame;import javax.swing.JLabel;public class KeyEventTest extends JFrame{ JLabel j1=new JLabel("您输入的东西:"); KeyEventTest() { Container main=getContentPane(); main.setLayout(new GridLayout(2,1)); main.add(j1); main.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { int i=e.getKeyCode(); String s=e.getKeyModifiersText(1); j1.setText(s); if(e.getKeyChar()=='a') System.out.print(i); } }); } public static void main(String[] args) { JFrame f=new KeyEventTest(); f.setBounds(100,100,300,250); f.setVisible(true); }}
本身想实现键盘输入然后在label标签里面显示,但是实际上在键盘上按什么反应的都没有,高人支招!!!!!!!!!!!!
------解决方案--------------------
感觉是事件监听器注册错了位置吧?
请把:
main.addKeyListener(new KeyAdapter()
修改为:
this.addKeyListener(new KeyAdapter()
另外,应该用:e.getKeyChar() 而不是 e.getKeyCode();