gpt4 book ai didi

java - 我的 (Java/Swing) MouseListener 没有监听,请帮我找出原因

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:16 26 4
gpt4 key购买 nike

所以我有一个 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 程序员(这是作业的一部分),但我看不到任何明显的东西。比我聪明的人能看到什么吗?

最佳答案

implements mouselistener, mousemotionlistener 只允许 displayArea 类监听一些要定义的 Swing 组件的鼠标事件。您必须明确定义它应该收听的内容。所以我想你可以在构造函数中添加这样的东西:

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

关于java - 我的 (Java/Swing) MouseListener 没有监听,请帮我找出原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com