Exercise
- 14 (Event Handling)
a).Write a JAVA program that display the x
and y position of the cursor movement using
Mouse.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class AppletMouse extends Applet implements MouseListener, MouseMotionListener
{
int x, y;
String str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// override ML 5 abstract methods
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Released";
repaint();
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Exited";
repaint();
}
// override two abstract methods of MouseMotionListener
public void mouseMoved(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse dragged";
repaint();
}
// called by repaint() method
public void paint(Graphics g)
{
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.fillOval(x, y, 10, 10);
g.drawString(x + "," + y, x+10, y -10);
g.drawString(str, x+10, y+20);
showStatus(str + " at " + x + "," + y);
}
}
Applet code:Applet code save as .html file
<html>
<body>
<applet code="AppletMouse.class" width="300" height="300">
</applet>
</body>
</html>
b).Write a JAVA program that identifies key-up key-down event user entering text in a Applet.
import java.applet.Applet;
import java.awt.*;
public class KeyUpDown1 extends Applet {
private Font f;
private String letter;
private boolean first;
public void init()
{
f = new Font( "Courier", Font.BOLD, 72 );
first = true;
}
public void paint( Graphics g )
{
g.setFont( f );
if ( !first )
g.drawString( letter, 75, 70 );
}
public boolean keyDown( Event e, int key )
{
showStatus( "keyDown: the " + ( char ) key +
" was pressed." );
letter = String.valueOf( ( char ) key );
first = false;
repaint();
return true; // event has been handled
}
public boolean keyUp( Event e, int key )
{
showStatus( "keyUp: the " + ( char ) key +
" was released." );
return true; // event has been handled
}
}
Applet code:Applet code save as .html
<html>
<body>
<applet code="KeyUpDown1.class" width="300" height="300">
</applet>
</body>
</html>
No comments:
Post a Comment