我的(Java / Swing)MouseListener没有在听,请帮我找出原因
时间:2020-03-05 18:44:45 来源:igfitidea点击:
所以我有一个JPanel
实现了MouseListener
和MouseMotionListener
:
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程序员(这是工作的一部分),但是我看不到任何明显的东西。有人能比我聪明吗?
解决方案
回答
该工具实现mouselistener,mousemotionlistener仅允许displayArea类侦听某些Swing组件的鼠标事件(即将定义)。我们必须明确定义它应该听的内容。因此,我想我们可以在构造函数中添加以下内容:
this.addMouseListener(this); this.addMouseMotionListener(this);
回答
我没有在代码中的任何地方看到我们为DisplayArea调用addMouseListener(this)或者addMouseMotionListener(this)以便订阅这些事件的代码。
回答
我在这里看不到任何代码可注册到鼠标侦听器。我们必须在DisplayArea上调用addMouseListener(this)和addMouseMotionListener(this)。