- import java.awt.FlowLayout;
- import java.awt.Frame;
- import java.awt.TextField;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- public class KeyListenerTest {
- KeyListenerTest()
- {
- init();
- }
-
- private Frame f;
- // private Button but;
- private TextField tf;
-
- public void init()
- {
- f=new Frame("keyListenerTest");
- f.setBounds(100,100,400,400);
- f.setLayout(new FlowLayout());
-
-
- // but=new Button("button");
-
- tf=new TextField(15);
-
- f.add(tf);
-
- myEvent();
-
- f.setVisible(true);
- }
- public void myEvent()
- {
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- tf.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- int code=e.getKeyCode();
- if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9))
- {
- e.consume();
- System.out.println(KeyEvent.getKeyText(code)+"无效");
- }
- }
- });
- }
- public static void main(String[] args) {
- new KeyListenerTest();
- }
- }
复制代码
看到老毕视频中关于consume()这段,我看视频中也差不多是这样的啊...为什么我这里无效..敲字母还是会在textfield中显示:o 环境是 ubuntu(kde下的)
难道跟系统有关?不能吧... |
|