5

我想在我的 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() 运行良好,但其他两个则没有(移动鼠标时控制台上没有显示)。谁能告诉我我做错了什么?提前致谢!

4

2 回答 2

17

如果要接收mouseMovedmouseDragged事件,还需要将侦听器注册为MouseMotionListener.

MouseAdapter adapter = ...
JFrame frame = ...
frame.addMouseListener(adapter);
frame.addMouseMotionListener(adapter);
于 2012-05-30T16:04:39.430 回答
1

也许您也应该尝试实施MouseMotionListenerand with MouseListener

于 2012-05-30T16:06:04.717 回答