Swing MouseMotionAdapter類

2019-10-16 22:11:09

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範例(tw511.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);
    }
}

執行上面範例程式碼,得到以下結果:

MouseMotionAdapter