Wednesday, 2 April 2014

KeyListener

The listener interface for receiving keyboard event.



public interface KeyListener extends EventListener {
    public void keyTyped(KeyEvent e);
    public void keyPressed(KeyEvent e);
    public void keyReleased(KeyEvent e);
}

void keyTyped(KeyEvent e)
Invoked when a key has been typed. See the class description for KeyEvent for a definition of a key typed event.

void keyPressed(KeyEvent e)
Invoked when a key has been pressed. See the class description for KeyEvent for a definition of a key pressed event.

void keyReleased(KeyEvent e)
Invoked when a key has been released. See the class description for KeyEvent for a definition of a key released event.


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;

public class KeyListenerEx1{
 JTextArea displayArea;
 JTextField typingArea;
 JFrame frame1;
  
 KeyListenerEx1(){
  
  /* Initialize typingArea */
  typingArea = new JTextField(20);
  
  /* Initialize Display Area */
  displayArea = new JTextArea();
  displayArea.setEditable(false);
  JScrollPane scrollPane = new JScrollPane(displayArea);
  scrollPane.setPreferredSize(new Dimension(375, 125));
   
  /* Initialize Frame */
  frame1 =new JFrame("Sample Frame");
  frame1.pack();
  frame1.setVisible(true);
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame1.getContentPane().add(typingArea, BorderLayout.PAGE_START);
  frame1.getContentPane().add(scrollPane, BorderLayout.CENTER);
  frame1.setSize(300, 500);
    
  /* Add Key Listener */
  typingArea.addKeyListener(new KeyListener(){
   public void keyTyped(KeyEvent e){
    displayArea.append("Key Typed\n" + e +"\n");
   }
    
   public void keyPressed(KeyEvent e){
    displayArea.append("Key Pressed\n " + e +"\n");
   }
    
   public void keyReleased(KeyEvent e){
    displayArea.append("Key Released\n" + e +"\n");
   }
  });   
 }
 
 public static void main(String args[]){
  new KeyListenerEx1();
 }
}

Output




 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment