Excersise:12 Key Event Handling | Java | Tamizhan Goals

Event Handling

Excersise: 12

    Event Handling Mechanism for Keyboard and Mouse .

Program


Keyboard Handling

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/**/
public class SimpleKey extends Applet implements KeyListener
{
String msg="";
int x=10,y=20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key up");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

Output


Mouse Event Handling

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/**/
public class MouseEvents extends Applet implements MouseListener,MouseMotionListener
{
String msg="";
int mouseX=0,mouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=0;
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=0;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=0;
mouseY=0;
msg="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at"+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
}

Output

Post a Comment

Thanks for your comments. Please be visit and given positive review on our site.

Previous Post Next Post