橘子味的心
标题:Swing MouseListener Interface

处理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示例(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 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) {
        }
    }
}

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


目录

分类