Create an
Applet that displays the x and y position of the cursor movement
using
Mouse and Keyboard. (Use appropriate listener)
import java.io.*;
import
java.applet.Applet;
import
java.awt.event.KeyAdapter;
import
java.awt.event.KeyEvent;
import
java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public
class MouseKeyboardPositionApplet extends Applet {
private int mouseX = 0;
private int mouseY = 0;
public void init() {
addMouseListener(new
MyMouseListener());
addKeyListener(new MyKeyListener());
setFocusable(true);
requestFocus();
}
public void paint(java.awt.Graphics g) {
g.drawString("Mouse Position:
(" + mouseX + ", " + mouseY + ")", 10, 20);
}
class MyMouseListener extends MouseAdapter
{
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
}
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() ==
KeyEvent.VK_UP) {
mouseY--;
} else if (e.getKeyCode() ==
KeyEvent.VK_DOWN) {
mouseY++;
} else if (e.getKeyCode() ==
KeyEvent.VK_LEFT) {
mouseX--;
} else if (e.getKeyCode() ==
KeyEvent.VK_RIGHT) {
mouseX++;
}
repaint();
}
}
}