Swing MouseMotionListener介面

2019-10-16 22:11:25

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程式:MouseMotionListenerDemo.java

package com.yiibai.swing.listener;

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

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

    public MouseMotionListenerDemo() {
        prepareGUI();
    }

    public static void main(String[] args) {
        MouseMotionListenerDemo swingListenerDemo = new MouseMotionListenerDemo();
        swingListenerDemo.showMouseMotionListenerDemo();
    }

    private void prepareGUI() {
        mainFrame = new JFrame("Java SWING MouseMotionListener範例(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 showMouseMotionListenerDemo() {
        headerLabel.setText("Listener in action: MouseMotionListener");

        JPanel panel = new JPanel();
        panel.setBackground(Color.blue);
        panel.setLayout(new FlowLayout());
        panel.addMouseMotionListener(new CustomMouseMotionListener());

        JLabel msglabel = new JLabel("歡迎您來到易百網Java/Swing教學~", 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() + ")");
        }
    }
}

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

MouseMotionListener