Swing MouseListener介面

2019-10-16 22:11:19

處理MouseEvent的類應該實現此介面。該類的物件必須在元件中註冊。可以使用addMouseListener()方法註冊該物件。

介面宣告

以下是java.awt.event.MouseListener介面的宣告 -

public interface MouseListener
   extends EventListener

介面方法

編號 方法 描述說明
1 void mouseClicked(MouseEvent e) 在元件上單擊(按下並釋放)滑鼠按鈕時呼叫。
2 void mouseEntered(MouseEvent e) 滑鼠進入元件時呼叫。
3 void mouseExited(MouseEvent e) 滑鼠退出元件時呼叫。
4 void mousePressed(MouseEvent e) 在元件上按下滑鼠按鈕時呼叫。
5 void mouseReleased(MouseEvent e) 在元件上釋放滑鼠按鈕時呼叫。

方法繼承

此介面從以下介面繼承方法 -

  • java.awt.EventListener

MouseListener範例

使用編輯器建立以下Java程式:MouseListenerDemo.java -

package com.yiibai.swing.listener;

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

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

    public MouseListenerDemo() {
        prepareGUI();
    }

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

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

        JPanel panel = new JPanel();
        panel.setBackground(Color.blue);
        panel.setLayout(new FlowLayout());
        panel.addMouseListener(new CustomMouseListener());

        JLabel msglabel = new JLabel("歡迎您來到易百教學!", JLabel.CENTER);
        panel.add(msglabel);

        msglabel.addMouseListener(new CustomMouseListener());
        panel.add(msglabel);

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

    class CustomMouseListener implements MouseListener {
        public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: (" + e.getX() + ", " + e.getY() + ")");
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }
    }
}

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

MouseListenerDemo