MouseListener Example in Java

In this example, We will show you simple application about, How to create Simple MouseListener Example in Java. The example output were shared in the same post.

#1 Creating Custom MouseListener

package com.dineshkrish.applet;
import java.applet.Applet;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyMouseListener implements MouseListener {
private Applet window = null;
public MyMouseListener(Applet window) {
this.window = window;
}
@Override
public void mouseClicked(MouseEvent e) {
window.setBackground(Color.red);
}
@Override
public void mouseEntered(MouseEvent e) {
window.setBackground(Color.yellow);
}
@Override
public void mouseExited(MouseEvent e) {
window.setBackground(Color.blue);
}
@Override
public void mousePressed(MouseEvent e) {
window.setBackground(Color.cyan);
}
@Override
public void mouseReleased(MouseEvent e) {
window.setBackground(Color.green);
}
}

#2 Testing with Applet Window

package com.dineshkrish.applet;
import java.applet.Applet;
public class MyApplet extends Applet {
MyMouseListener listener = new MyMouseListener(this);
public void init() {
addMouseListener(listener);
}
}

Output

MouseListener Example in Java

References

1. Java Applet
2. Java Events Documentation
3. Java MouseListener Documentation

No responses yet

Leave a Reply

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