在以下代码中,无法识别mouseDragged。我做错了什么?
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseDragged(MouseEvent e) { ... }
@Override
public void mousePressed(MouseEvent e) { ... }
});
答案 0 :(得分:7)
MouseInputAdapter mia = new MouseInputAdapter() {
@Override
public void mouseDragged(MouseEvent e) { ... }
@Override
public void mousePressed(MouseEvent e) { ... }
};
addMouseListener(mia);
addMouseMotionListener(mia); // <-- You're missing this one.
答案 1 :(得分:4)
由于您正在mouseDragged
内部实施addMouseListener
,因此无法识别。
mouseDragged
由MouseMotionListener
触发,mousePressed
由MouseListener
触发。
因此,您需要实现MouseListener
和MouseMotionListener
并相应地添加正确的侦听器。
public class MyClass extends JPanel implements MouseListener,
MouseMotionListener {
public MyClass() {
// whatever code you need, then add the listeners
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) { ... }
public void mouseDragged(MouseEvent e) { ... }
}
答案 2 :(得分:0)
不要使用addMouseListener,而是使用addMouseMotionListener:
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
});
:d