Java - Swing中的mouseMoved()事件处理

时间:2012-05-30 16:00:51

标签: java swing event-handling mouseevent mouse-listeners

我想在JFrame中监听鼠标移动和点击。为此,我添加了一个像这样实现的MouseListener :( View类的整个代码位于https://gist.github.com/2837224,Board类位于https://gist.github.com/2837231

class BattleshipsFrame extends JFrame {
  private final Board playerBoard, opponentBoard;
  private View view;

/** Main window constructor. */
BattleshipsFrame() {
  ...
  ...   
  ...
  //creating and displaying boards
  playerBoard = new Board();
  opponentBoard = new Board();
  PlayerBoardListener mouseListener = new PlayerBoardListener();
  this.addMouseListener(mouseListener);
  playerBoard.addMouseListener(mouseListener);
  opponentBoard.addMouseListener(new OpponentBoardListener());
  boards.add(playerBoard);
  boards.add(opponentBoard);
  ...
  ...
  ...
}

/** Listener responsible for handling mouse events on player board */
private class PlayerBoardListener extends MouseAdapter {
  @Override public void mousePressed(MouseEvent event) {
    try {
      if(event.getButton() == MouseEvent.BUTTON1 && controllerConnection != null)
        controllerConnection.sendShipPlacedEvent(event.getX()/40, event.getY()/40, ShipType.EMPTY);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }   
  @Override public void mouseMoved(MouseEvent event) {
    //TODO
    System.out.println("Mouse movement detected! Actual mouse position is: " + event.getX()+ "," + event.getY() + ".");
  }   
  @Override public void mouseDragged(MouseEvent event) {
    //TODO
    System.out.println("Mouse movement detected! Actual mouse position is: " + event.getX()+ "," + event.getY() + ".");
  }   

}

有趣的是,mousePressed()运行良好,但其他两个都没有(移动鼠标时控制台上没有显示)。任何人都可以告诉我,我做错了什么?提前谢谢!

2 个答案:

答案 0 :(得分:16)

如果您想接收mouseMovedmouseDragged个活动,则还需要将您的听众注册为MouseMotionListener

MouseAdapter adapter = ...
JFrame frame = ...
frame.addMouseListener(adapter);
frame.addMouseMotionListener(adapter);

答案 1 :(得分:1)

也许你应该尝试实施MouseMotionListenerMouseListener