By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 802 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

KeyPress

100+
P: 176
Hello guys. I was wondering how you make an event happen when the user presses a key. I have seen code used for this but I don't understand how it works.
Here is the code in a sample I found:
Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import java.awt.event.*;
  3.  
  4. public class KeyPress extends Frame{
  5.   Label label;
  6.   TextField txtField;
  7.   public static void main(String[] args) {
  8.     KeyPress k = new KeyPress();
  9.   }
  10.  
  11.   public KeyPress(){
  12.     super("Key Press Event Frame");
  13.     Panel panel = new Panel();
  14.     label = new Label();
  15.     txtField = new TextField(20);
  16.     txtField.addKeyListener(new MyKeyListener());
  17.     add(label, BorderLayout.NORTH);
  18.     panel.add(txtField, BorderLayout.CENTER);
  19.     add(panel, BorderLayout.CENTER);
  20.     addWindowListener(new WindowAdapter(){
  21.       public void windowClosing(WindowEvent we){
  22.         System.exit(0);
  23.       }
  24.     });
  25.     setSize(400,400);
  26.     setVisible(true);
  27.   }
  28.  
  29.   public class MyKeyListener extends KeyAdapter{
  30.     public void keyPressed(KeyEvent ke){
  31.       char i = ke.getKeyChar();
  32.       String str = Character.toString(i);
  33.       label.setText(str);
  34.     }
  35.   }  
  36.  
Could someone please explain to me how this works.
Apr 27 '08 #1
Share this Question
Share on Google+
1 Reply


100+
P: 539
The more detailed explanations about KeyListeners can be found here.

And also download the JAVA API documentations. it is useful.....

regards,
sukatoa
Apr 28 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.