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



我想在我的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()运行良好,但其他两个则不然(移动鼠标时控制台上没有显示任何内容)。任何人都可以告诉我我做错了什么?提前感谢!

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

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

也许你应该尝试实现MouseMotionListenerMouseListener

相关内容

  • 没有找到相关文章

最新更新