我正在制作一个需要用户输入鼠标的程序,因此我创建了一个扩展MouseAdapter的Mouse类。通过单击窗口进行测试时,它什么也没做。代码如下。任何帮助表示赞赏。
主类
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
add(new Window());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(720, 480);
setLocationRelativeTo(null);
setTitle("Mouse Input");
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new Main();
}
}
窗口类
public class Window extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
public Window() {
addMouseMotionListener(new Mouse());
Timer timer = new Timer(10, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
鼠标类
class Mouse extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked");
}
public void mouseDragged(MouseEvent e) {
System.out.println("Dragged");
}
}
答案 0 :(得分:2)
它在点击时不会执行任何操作,因为您已将其作为MouseMotionListener添加到JPanel但不是作为MouseListener添加。您还需要通过addMouseListener(...)
方法将Mouse实例传递到JPanel,以便发生MouseListener事件。
即,
public Window() {
Mouse myMouse = new Mouse();
addMouseMotionListener(myMouse); // you already have this
addMouseListener(myMouse); // **** add this!! ****
答案 1 :(得分:1)
addMouseMotionListener(new Mouse()); addMouseListener(new MouseListener(){
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("asdasd");
}
});