Handling Mouse Events in Java…
Example : MouseEvents
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents"width=300 height=100> </applet> */ public class MouseEvents extends java.applet.Applet implements MouseListener,MouseMotionListener { String msg=""; int mouseX=0,mouseY=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouse(MouseEvent me) { mouseX=0; mouseY=10; msg="Mouse ."; repaint(); } public void mouseClicked(MouseEvent me) { mouseX=0; mouseY=10; msg="Mouse clicked ."; repaint(); } public void mouseEntered(MouseEvent me) { mouseX=0; mouseY=10; msg="Mouse entered ."; repaint(); } public void mouseExited(MouseEvent me) { mouseX=0; mouseY=10; msg="Mouse exited ."; repaint(); } public void mousePressed(MouseEvent me) { mouseX=0; mouseY=10; msg="Mouse pressed ."; 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); } }
Keyboard Events in Java…
Example : SimpleKey
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="SimpleKey"width=300 height=100> </applet> */ public class SimpleKey extends java.applet.Applet implements KeyListener { String msg=""; int X=10,Y=20; public void init() { addKeyListener(this); requestFocus(); } 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); } }
Adapter Classes in Java…
Example : MouseAdapterDemo
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="MouseAdapterDemo"width=100 height=100> </applet> */ public class MouseAdapterDemo extends java.applet.Applet { public void init() { setBackground(Color.green); addMouseListener(new MyMouseAdapter(this)); } } class MyMouseAdapter extends MouseAdapter { MouseAdapterDemo m; public MyMouseAdapter(MouseAdapterDemo m) { this.m=m; } public void mousePressed(MouseEvent me) { m.setBackground(Color.red); m.repaint(); } public void mouseReleased(MouseEvent me) { m.setBackground(Color.green); m.repaint(); } }