SWING - 鼠标移动监听器接口



简介

MouseMotionListener 接口用于在组件上接收鼠标移动事件。需要处理鼠标移动事件的类需要实现此接口。

类声明

以下是 java.awt.event.MouseMotionListener 接口的声明 -

public interface MouseMotionListener
extends EventListener

接口方法

序号 方法和描述
1

void mouseDragged(MouseEvent e)

在组件上按下鼠标按钮并拖动时调用。

2

void mouseMoved(MouseEvent e)

在鼠标光标移动到组件上但未按下任何按钮时调用。

继承的方法

此类继承以下接口的方法 -

java.awt.event.EventListener

MouseMotionListener 示例

在您选择的任何编辑器中创建以下 Java 程序,例如在 D:/ > SWING > com > tutorialspoint > gui >

SwingListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingListenerDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingListenerDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showMouseMotionListenerDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        
      statusLabel.setSize(350,100);
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showMouseMotionListenerDemo(){
      headerLabel.setText("Listener in action: MouseMotionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());
      
      JLabel msglabel 
         = new JLabel("Welcome to TutorialsPoint SWING Tutorial.",JLabel.CENTER);        
      
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
   class CustomMouseMotionListener implements MouseMotionListener {
      public void mouseDragged(MouseEvent e) {
         statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
      }
      public void mouseMoved(MouseEvent e) {
         statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
      }    
   }
}

使用命令提示符编译程序。转到 D:/ > SWING 并键入以下命令。

D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java

如果没有错误出现,则表示编译成功。使用以下命令运行程序。

D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo

验证以下输出。

SWING MouseMotionListener
swing_event_listeners.htm
广告