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);

以上是 Java-Swing中的mouseMoved()事件处理 的全部内容, 来源链接: utcz.com/qa/413606.html

回到顶部