当前位置:  开发笔记 > 编程语言 > 正文

我的(Java/Swing)MouseListener没有听,请帮我搞清楚原因

如何解决《我的(Java/Swing)MouseListener没有听,请帮我搞清楚原因》经验,为你挑选了1个好方法。

所以我有一个JPanel实现MouseListenerMouseMotionListener:

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

public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener  {
    public DisplayArea(Rectangle bounds, Display display) {
        setLayout(null);
        setBounds(bounds);
        setOpaque(false);
        setPreferredSize(new Dimension(bounds.width, bounds.height));

        this.display = display;
    }

    public void paintComponent(Graphics g) {
         Graphics2D g2 = (Graphics2D)g;
         if (display.getControlPanel().Antialiasing()) {
             g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
         }
         g2.setColor(Color.white);
         g2.fillRect(0, 0, getWidth(), getHeight());
    }

    public void mousePressed(MouseEvent event) {
        System.out.println("mousePressed()");
        mx1 = event.getX();
        my1 = event.getY();
    }

    public void mouseReleased(MouseEvent event) {
        System.out.println("mouseReleased()");
        mx2 = event.getX();
        my2 = event.getY();

        int mode = display.getControlPanel().Mode();
        switch (mode) {
        case ControlPanel.LINE:
             System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + ".");
        }
    }

    public void mouseEntered(MouseEvent event) {
        System.out.println("mouseEntered()");
    }

    public void mouseExited(MouseEvent event) {
        System.out.println("mouseExited()");
    }

    public void mouseClicked(MouseEvent event) {
        System.out.println("mouseClicked()");
    }

    public void mouseMoved(MouseEvent event) {
        System.out.println("mouseMoved()");
    }

    public void mouseDragged(MouseEvent event) {
         System.out.println("mouseDragged()");
    }

    private Display display = null;

    private int mx1 = -1;
    private int my1 = -1;
    private int mx2 = -1;
    private int my2 = -1;
}

问题是,这些鼠标功能都没有被调用过.DisplayArea像这样创建:

da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this);

我不是一个真正的Java程序员(这是一个任务的一部分),但我看不出任何明显的东西.有人比我看到更聪明吗?



1> Shabaz..:

工具的MouseListener,的MouseMotionListener只允许displayArea类听一些,要定义,Swing组件的鼠标事件.你必须明确定义它应该听的内容.所以我想你可以在构造函数中添加这样的东西:

this.addMouseListener(this);
this.addMouseMotionListener(this);

推荐阅读
雨天是最美
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有