Friday, May 3, 2019

keyboard handling

1.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet
implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}


<applet code="Key" width=200 height=60>
</applet>







Example2:


import java.awt.*;

import java.applet.*;



public class Key1 extends Applet

{

    int keyPressed;



    public void init()

    {

        keyPressed = -1;



        Font font =  new Font("TimesRoman", Font.BOLD, 144);

        setFont(font);



        resize(200, 200);

    }



    public void paint(Graphics g)

    {

        String str = "";



        if (keyPressed != -1)

        {

            str += (char)keyPressed;

            g.drawString(str, 40, 150);

        }

    }



    public boolean keyDown(Event evt, int key)

    {

        keyPressed = key;

        repaint();

        return true;

    }

}

<applet code="Key1" width=200 height=60>
</applet>


No comments:

Post a Comment