gpt4 book ai didi

java - java中的鼠标输入问题

转载 作者:行者123 更新时间:2023-11-30 11:03:34 26 4
gpt4 key购买 nike

编辑:我有一个应用程序使用 swing Timer 来控制 Action 监听器界面何时触发。鼠标逻辑有效,但偶尔不会检测到点击。下面是我的注释代码。

public class Board extends JPanel implements MouseListener, MouseMotionListener, ActionListener
{
private MainMenu mainMenu = new MainMenu();
private static String State; /*Makes the control flow simpler, just checking
strings that describe the state. All the states are contained in GameState class.*/
public Board()
{

this.addMouseListener(this);
this.addMouseMotionListener(this);
setVisible(true);

mainMenu.initLogIn(); /*This just loads the button images*/
Timer timer = new Timer(12, this); /*(millisecond delay, tells this class
to update any actionlistener (mouselistener etc)*/
timer.start();
}


public void paint(Graphics G)
{
super.paint(G);
Graphics G2d = (Graphics2D)G;
/*Main menu paint logic*/

// This paints buttons from mainMenu class on screen
G.drawImage(mainMenu.getTopic1().getspriteImage(),
mainMenu.getTopic1().getxCoord(),
mainMenu.getTopic1().getyCoord(),this);
G.drawImage(mainMenu.getTopic2().getspriteImage(),
mainMenu.getTopic2().getxCoord(),
mainMenu.getTopic2().getyCoord(), this);
G.drawImage(mainMenu.getTopic3().getspriteImage(),
mainMenu.getTopic3().getxCoord(),
mainMenu.getTopic3().getyCoord(),this);
/*Shows mouse input worked by changing the background color*/
if (State == GameState.MAINMENU_TOPIC1)
{
setBackground(Color.BLACK);
}
if (State == GameState.MAINMENU_TOPIC2)
{
setBackground(Color.BLUE);
}
if (State == GameState.MAINMENU_TOPIC3)
{
setBackground(Color.GRAY);
}
repaint(); //tells paint to repaint, which allows gui to update

}
@Override
public void mouseClicked(MouseEvent e)
{
Point point = e.getPoint();
/*This contains the logic to change State based on mouse clicks*/

if(mainMenu.getTopic1().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC1;
}
if(mainMenu.getTopic2().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC2;
}
if(mainMenu.getTopic3().getRectangle().contains(point))
{
State = GameState.MAINMENU_TOPIC3;
}
}

所以,我不确定为什么不能总是检测到鼠标点击。我知道分配给更新 Action 监听器的时间可能太短了。但是,机器循环的代码并不多,所以我认为这不是问题所在。关于什么可能导致鼠标以这种方式运行的任何想法?

此外,我稍后肯定会使用 JButtons 来实现它。我确信这将有助于在更大的项目中清理我的代码

感谢您的评论,我希望这能解决大部分问题。

最佳答案

鼠标“单击”本质上可能是双击或三次单击。您可以使用 evt.clickCount 获取它。它将合并为一个事件。

如果你想获得每一次“按下”,请改用 mousePressed()

关于java - java中的鼠标输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30308113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com