Practical 10: Write a program to demonstrate status of key on Applet window such as KeyPressed, KeyReleased, KeyUp, KeyDown

1)Write a program to demonstrate status of key on Applet window such as KeyPressed, KeyReleased, KeyUp, KeyDown

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class KeyEventDemo extends Applet implements KeyListener
{
    String msg = "";

    public void init()
    {
        addKeyListener(this);
    }

    public void keyReleased(KeyEvent k)
    {
        showStatus("Key Released");
        repaint();
    }

    public void keyTyped(KeyEvent k)
    {
        showStatus("Key Typed");
        repaint();
    }

    public void keyPressed(KeyEvent k)
    {
        showStatus("Key Pressed");
        repaint();
    }

    public void paint(Graphics g)
    {
        g.drawString(msg, 10, 10);
    }
}
/* 
   <applet code="KeyEventDemo" height="400" width="400">
   </applet>
*/



Output:
KeyEvent show in status

 2) Develop a program which will implement special keys such as function keys and arrow keys.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class KeyEventDemo extends Applet implements KeyListener
{
    String msg = "";

    public void init()
    {
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent k)
    {
        int key = k.getKeyCode();

        switch(key)
        {
            case KeyEvent.VK_F1:
                msg = msg + "F1 ";
                break;
            case KeyEvent.VK_F2:
                msg = msg + "F2 ";
                break;
            case KeyEvent.VK_F3:
                msg = msg + "F3 ";
                break;
            case KeyEvent.VK_F4:
                msg = msg + "F4 ";
                break;
            case KeyEvent.VK_RIGHT:
                msg = msg + "RIGHT ";
                break;
            case KeyEvent.VK_LEFT:
                msg = msg + "LEFT ";
                break;
            case KeyEvent.VK_UP:
                msg = msg + "UP ";
                break;
            
            case KeyEvent.VK_DOWN:
                msg = msg + "DOWN ";
                break;

        }

        repaint();
    }

    public void keyReleased(KeyEvent k){}

    public void keyTyped(KeyEvent k){}

    public void paint(Graphics g)
    {
        g.drawString(msg, 10, 10);
    }
}

/* 
   <applet code="KeyEventDemo" height=400 width=400>
   </applet>
*/




Output:

Key Pressed Event

Previous
Next Post »