橘子味的心
标题:Swing MouseMotionAdapter类

MouseMotionAdapter类是一个抽象(适配器)类,用于接收鼠标移动事件。此类的所有方法都是空的。此类是用于创建侦听器对象的便捷类。

类声明

以下是java.awt.event.MouseMotionAdapter类的声明 -

public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener

类构造函数

编号 构造方法 描述
1 MouseMotionAdapter() 无参数构造函数

类方法

编号 方法 描述
1 void mouseDragged(MouseEvent e) 在组件上按下鼠标按钮然后拖动时调用。
2 void mouseMoved(MouseEvent e) 将鼠标光标移动到组件但未按下任何按钮时调用。

方法继承

该类继承以下类中的方法 -

  • java.lang.Object

MouseMotionAdapter示例

使用编辑器创建以下Java程序:MouseMotionAdapterDemo.java

package com.yiibai.swing.listener;

import javax.swing.*;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;

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

    public MouseMotionAdapterDemo() {
        prepareGUI();
    }

    public static void main(String[] args) {
        MouseMotionAdapterDemo swingAdapterDemo = new MouseMotionAdapterDemo();
        swingAdapterDemo.showMouseMotionAdapterDemo();
    }

    private void prepareGUI() {
        mainFrame = new JFrame("Java SWING MouseMotionAdapter示例(yiibai.com)");
        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 showMouseMotionAdapterDemo() {
        headerLabel.setText("Listener in action: MouseMotionAdapter");
        JPanel panel = new JPanel();
        panel.setBackground(Color.blue);
        panel.setLayout(new FlowLayout());

        panel.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                statusLabel.setText("Mouse Moved: (" + e.getX() + ", " + e.getY() + ")");
            }
        });
        JLabel msglabel = new JLabel("欢迎您来到易百教程Swing~)", JLabel.CENTER);

        panel.add(msglabel);
        controlPanel.add(panel);
        mainFrame.setVisible(true);
    }
}

执行上面示例代码,得到以下结果:


目录

分类