MouseListener y MouseMotionListener es una interfaz en el paquete java.awt.event. Los eventos de ratón
son de dos tipos. MouseListener maneja los eventos cuando el mouse no está en movimiento. Mientras que MouseMotionListener
maneja los eventos cuando el mouse está en movimiento.
Hay cinco tipos de eventos que puede generar MouseListener. Hay cinco funciones abstractas que representan estos cinco eventos. Las funciones abstractas son:
- void mouseReleased(MouseEvent e) : se suelta la tecla del mouse
- void mouseClicked(MouseEvent e) : Se presiona/suelta la tecla del mouse
- void mouseExited(MouseEvent e) : El mouse salió del componente
- void mouseEntered(MouseEvent e) : El mouse ingresó al componente
- void mousepressed(MouseEvent e) : Se presiona la tecla del mouse
Hay dos tipos de eventos que puede generar MouseMotionListener. Hay dos funciones abstractas que representan estos cinco eventos. Las funciones abstractas son:
- void mouseDragged(MouseEvent e) : se invoca cuando se presiona un botón del mouse en el componente y se arrastra. Los eventos se pasan hasta que el usuario suelta el botón del ratón.
- void mouseMoved(MouseEvent e) : se invoca cuando el cursor del mouse se mueve de un punto a otro dentro del componente, sin presionar ningún botón del mouse.
Los siguientes programas son una ilustración de MouseListener y MouseMotionListener.
1. Programa para manejar eventos MouseListener
Java
// Java program to handle MouseListener events import java.awt.*; import java.awt.event.*; import javax.swing.*; class Mouse extends Frame implements MouseListener { // Jlabels to display the actions of events of mouseListener // static JLabel label1, label2, label3; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseListener"); // set the size of the frame f.setSize(600, 100); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); label3 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseListener(m); // add labels to the panel p.add(label1); p.add(label2); p.add(label3); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label1.setText("mouse pressed at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label1.setText("mouse released at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label2.setText("mouse exited through point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label2.setText("mouse entered at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label3.setText("mouse clicked at point:" + e.getX() + " " + e.getY() + "mouse clicked :" + e.getClickCount()); } }
Producción :
Nota: Es posible que el siguiente programa no se ejecute en un compilador en línea. Utilice un IDE sin conexión. Tomemos
otro ejemplo en MouseListener . La pregunta es:
P. Escriba un subprograma que muestre las coordenadas x e y en su barra de estado cada vez que el usuario haga clic en cualquier lugar. en la ventana del Applet.
Respuesta
Nota: Este código es con respecto a Netbeans IDE.
Java
//Program of an applet which //displays x and y co-ordinate //in it's status bar,whenever //the user click anywhere in //the applet window. import java.awt.*; import java.awt.event.*; import java.applet.*; public class GFG extends Applet implements MouseListener { public void init() { this.addMouseListener (this); //first "this" represent source //(in this case it is applet which //is current calling object) and //second "this" represent //listener(in this case it is GFG) } public void mouseClicked(MouseEvent m) { int x = m.getX(); int y = m.getY(); String str = "x =" +x+",y = "+y; showStatus(str); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
Producción:
Modificación: ahora nuestro objetivo es mejorar el programa anterior para que las coordenadas se muestren en ese punto solo donde se hizo clic.
Nota: este código es con respecto a Netbeans IDE.
Java
//Co-ordinates should display //at that point only wherever //their is click on canvas import java.awt.*; import java.awt.event.*; import java.applet.*; public class GFG extends Applet implements MouseListener { private int x,y; private String str = " "; public void init() { this.addMouseListener (this); //first "this" represent source //(in this case it is applet which // is current calling object) and // second "this" represent listener //(in this case it is GFG) } public void paint(Graphics g) { g.drawString(str,x,y); } public void mouseClicked(MouseEvent m) { x = m.getX(); y = m.getY(); str = "x =" +x+",y = "+y; repaint(); // we have made this //call because repaint() will //call paint() method for us. //If we comment out this line, //then we will see output //only when focus is on the applet //i.e on maximising the applet window //because paint() method is called //when applet screen gets the focus. //repaint() is a method of Component //class and prototype for this method is: //public void repaint() } public void mouseEntered(MouseEvent m) //over-riding all the methods given by // MouseListener { } public void mouseExited(MouseEvent m) { } public void mousePressed(MouseEvent m) { } public void mouseReleased(MouseEvent m) { } }
Producción
Ahora aparecerá una cosa más inusual en la salida , que es que no podremos ver las coordenadas anteriores. Pero, ¿por qué?
En Java, antes de llamar al método paint(), llama a un método más que es update() y hace lo siguiente:
- vuelve a pintar el fondo del applet con el color actual.
- luego llama a paint().
Ahora, para ver también las coordenadas anteriores:
también tenemos que anular el método update() y su prototipo es similar a paint().
Modificación adicional Para ver también las coordenadas anteriores:
Nota: Este código es con respecto a Netbeans IDE.
Java
//Co-ordinates should display //at that point only wherever //their is click on canvas and also //able to see the previous coordinates import java.awt.*; import java.awt.event.*; import java.applet.*; public class GFG extends Applet implements MouseListener { private int x,y; private String str = " "; public void init() { this.addMouseListener (this); } public void paint(Graphics g) { g.drawString(str,x,y); } public void update(Graphics g) { paint(g); } public void mouseClicked(MouseEvent m) { x = m.getX(); y = m.getY(); str = "x =" +x+",y = "+y; repaint(); } public void mouseEntered(MouseEvent m) { } public void mouseExited(MouseEvent m) { } public void mousePressed(MouseEvent m) { } public void mouseReleased(MouseEvent m) { } }
Producción
2. Programa para manejar eventos MouseMotionListener
Java
// Java Program to illustrate MouseMotionListener events import java.awt.*; import java.awt.event.*; import javax.swing.*; class Mouse extends Frame implements MouseMotionListener { // Jlabels to display the actions of events of MouseMotionListener static JLabel label1, label2; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseMotionListener"); // set the size of the frame f.setSize(600, 400); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); // set the layout of the panel p.setLayout(new FlowLayout()); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener to the frame f.addMouseMotionListener(m); // add labels to the panel p.add(label1); p.add(label2); // add panel to the frame f.add(p); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText("mouse is dragged through point " + e.getX() + " " + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText("mouse is moved to point " + e.getX() + " " + e.getY()); } }
Producción :
3. Programa Java para ilustrar eventos MouseListener y MouseMotionListener
simultáneamente
Java
// Java program to illustrate MouseListener // and MouseMotionListener events // simultaneously import java.awt.*; import java.awt.event.*; import javax.swing.*; class Mouse extends Frame implements MouseMotionListener, MouseListener { // Jlabels to display the actions of events of MouseMotionListener and MouseListener static JLabel label1, label2, label3, label4, label5; // default constructor Mouse() { } // main class public static void main(String[] args) { // create a frame JFrame f = new JFrame("MouseListener and MouseMotionListener"); // set the size of the frame f.setSize(900, 300); // close the frame when close button is pressed f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create anew panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // set the layout of the frame f.setLayout(new FlowLayout()); JLabel l1, l2; l1 = new JLabel("MouseMotionListener events :"); l2 = new JLabel("MouseLIstener events :"); // initialize the labels label1 = new JLabel("no event "); label2 = new JLabel("no event "); label3 = new JLabel("no event "); label4 = new JLabel("no event "); label5 = new JLabel("no event "); // create an object of mouse class Mouse m = new Mouse(); // add mouseListener and MouseMotionListenerto the frame f.addMouseMotionListener(m); f.addMouseListener(m); // add labels to the panel p.add(l1); p.add(label1); p.add(label2); p1.add(l2); p1.add(label3); p1.add(label4); p1.add(label5); // add panel to the frame f.add(p); f.add(p1); f.show(); } // getX() and getY() functions return the // x and y coordinates of the current // mouse position // getClickCount() returns the number of // quick consecutive clicks made by the user // MouseMotionListener events // invoked when mouse button is pressed // and dragged from one point to another // in a component public void mouseDragged(MouseEvent e) { // update the label to show the point // through which point mouse is dragged label1.setText("mouse is dragged through point " + e.getX() + " " + e.getY()); } // invoked when the cursor is moved from // one point to another within the component public void mouseMoved(MouseEvent e) { // update the label to show the point to which the cursor moved label2.setText("mouse is moved to point " + e.getX() + " " + e.getY()); } // MouseListener events // this function is invoked when the mouse is pressed public void mousePressed(MouseEvent e) { // show the point where the user pressed the mouse label3.setText("mouse pressed at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is released public void mouseReleased(MouseEvent e) { // show the point where the user released the mouse click label3.setText("mouse released at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse exits the component public void mouseExited(MouseEvent e) { // show the point through which the mouse exited the frame label4.setText("mouse exited through point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse enters the component public void mouseEntered(MouseEvent e) { // show the point through which the mouse entered the frame label4.setText("mouse entered at point:" + e.getX() + " " + e.getY()); } // this function is invoked when the mouse is pressed or released public void mouseClicked(MouseEvent e) { // getClickCount gives the number of quick, // consecutive clicks made by the user // show the point where the mouse is i.e // the x and y coordinates label5.setText("mouse clicked at point:" + e.getX() + " " + e.getY() + "mouse clicked :" + e.getClickCount()); } }
producción :
MouseListener frente a MouseMotionListener
- MouseListener: los eventos MouseListener se invocan cuando el mouse no está en movimiento y está estable . Genera eventos como mousePressed, mouseReleased, mouseClicked, mouseExited y mouseEntered (es decir, cuando se presionan los botones del mouse o el mouse ingresa o sale del componente). El objeto de esta clase debe estar registrado con el componente y se registran utilizando el método addMouseListener().
- MouseMotionListener: los eventos MouseMotionListener se invocan cuando el mouse está en movimiento . Genera eventos como mouseMoved y mouseDragged (es decir, cuando el mouse se mueve de un punto a otro dentro del componente o el botón del mouse se presiona y se arrastra de un punto a otro). El objeto de esta clase debe estar registrado con el componente y se registran utilizando el método addMouseMotionListener().
Publicación traducida automáticamente
Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA