KeyPress

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kid Programmer
    New Member
    • Mar 2008
    • 176

    #1

    KeyPress

    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:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    
    public class KeyPress extends Frame{
      Label label;
      TextField txtField;
      public static void main(String[] args) {
        KeyPress k = new KeyPress();
      }
    
      public KeyPress(){
        super("Key Press Event Frame");
        Panel panel = new Panel();
        label = new Label();
        txtField = new TextField(20);
        txtField.addKeyListener(new MyKeyListener());
        add(label, BorderLayout.NORTH);
        panel.add(txtField, BorderLayout.CENTER);
        add(panel, BorderLayout.CENTER);
        addWindowListener(new WindowAdapter(){
          public void windowClosing(WindowEvent we){
            System.exit(0);
          }
        });
        setSize(400,400);
        setVisible(true);
      }
    
      public class MyKeyListener extends KeyAdapter{
        public void keyPressed(KeyEvent ke){
          char i = ke.getKeyChar();
          String str = Character.toString(i);
          label.setText(str);
        }
      }
    Could someone please explain to me how this works.
  • sukatoa
    Contributor
    • Nov 2007
    • 539

    #2
    The more detailed explanations about KeyListeners can be found here.

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

    regards,
    sukatoa

    Comment

    Working...