|
interface MouseListener { void mouseClicked(MouseEvent e); // Called when Mouse clicked void mouseEntered(MouseEvent e); // Called when Mouse enters component void mouseExited(MouseEvent e); // Called when Mouse exits component void mousePressed(MouseEvent e); // Called when Mouse was pressed void mouseReleased(MouseEvent e); // Called when Mouse released } |
class myMouseListener implements MouseListener { public void mouseClicked(MouseEvent event) { System.out.println("Mouse clicked @ position x = " + event.getX() + " y = " + event.getY()); } public void mouseEntered(MouseEvent event) { System.out.println("Mouse entered. x = " + event.getX() + " y = " + event.getY()); } public void mouseExited(MouseEvent event) { System.out.println("Mouse exited. x = " + event.getX() + " y = " + event.getY()); } public void mousePressed(MouseEvent event) { System.out.println("Mouse pressed. x = " + event.getX() + " y = " + event.getY()); } public void mouseReleased(MouseEvent event) { System.out.println("Mouse released. x = " + event.getX() + " y = " + event.getY()); } } |
Note:
|
|
Examples:
Callback Interface | Callback Registering method name |
---|---|
MouseListener | addMouseListener() |
ActionListener | addActionListener() |
and so on... | and so on... |
JFrame f = new JFrame("Active frame !"); myMouseListener x = new myMouseListener(); f.addMouseListener( x ); |
public class MouseSpyAppl { public static void main(String[] args) { JFrame f = new JFrame("Mouse Test"); f.setSize(300, 300); f.setVisible(true); } } |
public static class myMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent event)
{
System.out.println("Mouse clicked @ position x = "
+ event.getX() + " y = " + event.getY());
}
public void mouseEntered(MouseEvent event)
{ System.out.println("Mouse entered. x = "
+ event.getX() + " y = " + event.getY());
}
public void mouseExited(MouseEvent event)
{ System.out.println("Mouse exited. x = "
+ event.getX() + " y = " + event.getY());
}
public void mousePressed(MouseEvent event)
{ System.out.println("Mouse pressed. x = "
+ event.getX() + " y = " + event.getY());
}
public void mouseReleased(MouseEvent event)
{ System.out.println("Mouse released. x = "
+ event.getX() + " y = " + event.getY());
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // You need to import this class !
public class MouseSpyAppl
{
public static void main(String[] args)
{
JFrame f = new JFrame("Mouse Test");
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Register the CallBack Interface class (below)
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
f.addMouseListener(new myMouseListener() );
f.setSize(300, 300);
f.setVisible(true);
}
}
|
(You can teach GUI programming to high scholers nowadays...)