所以我尝试使用 Java 图形创建一个视频游戏,并且我需要使用 MouseListener 作为菜单屏幕上的“播放”按钮。当我按下按钮时,只要我按住按钮,它就会重复打印测试文本。我认为这就像编写只允许打印一次的代码一样简单,但我不知道如何做到这一点。
我尝试添加返回方法,但没有成功。 我还尝试将 MouseListener 语句移至 mouseClicked、mouseEntered、mouseExited 和 mouseReleased,但没有成功 我过去确实遇到过类似的问题,除了用打开其他窗口替换打印语句之外。
这是 MouseListener 语句
public void mousePressed(MouseEvent e) {
if ((e.getButton() == 1)
&& (e.getX() >= Playx1 && e.getX() <= Playx1 + Playw1 && e.getY() >= Playy1 && e
.getY() <= Playy1 + Playh1)) {
System.out.println("Test Text, Replace line with method later");
}
}
动画循环可能很重要,我不知道
private Thread animationThread = new Thread(new Runnable() {
public void run() {
while (true) {
repaint();
try {Thread.sleep(10);} catch (Exception ex) {}
}
}
});
我希望当我按下按钮时仅显示一次“测试文本,稍后用方法替换行”,但相反,只要我按下按钮,它就会一直显示。
最佳答案
我会按如下方式解决它:
AtomicBoolean buttonIsPressed = new AtomicBoolean( false );
public void mousePressed( MouseEvent e )
{
if( ((e.getButton() == 1)
&& (e.getX() >= Playx1 && e.getX() <= Playx1 + Playw1 && e.getY() >= Playy1 &&
e.getY() <= Playy1 + Playh1))
&& !buttonIsPressed.compareAndExchange( false, true ) )
{
System.out.println("Test Text, Replace line with method later");
}
}
public void mouseReleased( MouseEvent e )
{
if( e.getButton() == 1 )
{
buttonIsPressed.compareAndExchange( true, false );
}
}
我认为这就是 @inquizitive 的评论的意思。
关于java - MouseListener 多次打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841137/