Java - AWT MouseListener Interface


Java MouseListener je obaviješten kad god promijenite stanje miša. Prijavljen je protiv MouseEventa. Interfejs MouseListener se nalazi u paketu java.awt.event. Ima pet metoda. Potpis 5 metoda za MouseListener interfejsu je prikazan u nastavku:

public abstract void mouseClicked(MouseEvent e);  
public abstract void mouseEntered(MouseEvent e);  
public abstract void mouseExited(MouseEvent e);  
public abstract void mousePressed(MouseEvent e);  
public abstract void mouseReleased(MouseEvent e);  


Primjer Java MouseListener-a

import java.awt.*;  
import java.awt.event.*;  

public class Main extends Frame implements MouseListener{  
    Label l;  
    Main(){  
        addMouseListener(this);  
          
        l=new Label();  
        l.setBounds(20,50,200,20);  
        add(l);  
        setSize(300,300);  
        setLayout(null);  
        setVisible(true);  
    }  
    public void mouseClicked(MouseEvent e) {  
        l.setText("Miš kliknut!");  
    }  
    public void mouseEntered(MouseEvent e) {  
        l.setText("Miš se nalazi u formi!");  
    }  
    public void mouseExited(MouseEvent e) {  
        l.setText("Miš se nalazi izvan forme!");  
    }  
    public void mousePressed(MouseEvent e) {  
        l.setText("Klik miša!");  
    }  
    public void mouseReleased(MouseEvent e) {  
        l.setText("Pušten taster miša!");  
    }  
    public static void main(String[] args) {  
        new Main();  
    }  
}

Prikaz koda iz gornjeg primjera izgledaće ovako:



Primjer 2 Java MouseListener-a

import java.awt.*;  
import java.awt.event.*;

public class Main extends Frame implements MouseListener{  
    Main(){  
        addMouseListener(this);  
          
        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) {}  
      
    public static void main(String[] args) {  
        new Main();  
    }  
}

Prikaz koda iz gornjeg primjera izgledaće ovako: