Demonstrate The Mouse Event Handlers
Demonstrate The Mouse Event Handlers
Demonstrate The Mouse Event Handlers
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
//Demonstrate MouseMotionListener
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener
{
MouseMotionListenerExample()
{
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
//Demonstrate MouseMotionListener
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MouseMotionListenerExample2 extends Frame implements
MouseMotionListener
{
Label l;
Color c=Color.BLUE;
MouseMotionListenerExample2()
{
l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e)
{
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e)
{
l.setText("X="+e.getX()+", Y="+e.getY());
}
public static void main(String[] args)
{
new MouseMotionListenerExample2();
}
}
//Demonstrate KeyListener
// importing awt libraries
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l = new Label();
l.setBounds (20, 50, 100, 20);
area.addKeyListener(this);
add(l);
add(area);
KeyListenerExample2()
{
l = new Label();
l.setBounds (20, 50, 200, 20);
area.addKeyListener(this);
add(l);
add(area);
//Demonstrate WindowListener
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;