Java Applets: Event Handling

The event handling mechanism is the same as the Java Application program. The following applet demonstrates this:

//MouseEventDemo.java import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class MouseEventDemo extends Applet implements MouseListener {

String msg = ‘”‘;

int x = 0, y = 0;

public void init() {

addMouseListener(this);

}

public void paint(Graphics g) {

g.drawString(msg, x, y);

}

public void mouseClicked(MouseEvent me) {

x = me.getX();

y = me.getY();

msg = “clicked”;

repaint();

}

public void mouseEntered(MouseEvent me) {

x = y = 10;

msg = “entered”;

repaint();

}

public void mouseExited(MouseEvent me) {

x = y = 10;

msg = “exited”;

repaint();

}

public void mousePressed(MouseEvent me) {

x = me.getX();

y = me.getY();

msg = “pressed”;

repaint();

}

public void mouseReleased(MouseEvent me) {

x = me.getX();

y = me.getY();

msg = “released”;

repaint();

}

}

Now create the following applet, which results in the output shown in Figure 16.16:

<applet code=”MouseEventDemo” width=”200″ height=”50″>

</applet>

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *