gpt4 book ai didi

java - 模拟鼠标事件

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

我想模拟鼠标在图形上的点击。我添加了一个鼠标监听器,以及鼠标单击完成时的一些操作,但我确实需要模拟用户在程序中单击我的图形...我怎么能说““MouseEvent e 已执行!””之类的内容?

实际上,当您单击名为“Clean”的 Jbutton 时,我想清理“Graphics 2D canvas”。但问题是,只有当用户单击我的“图形 2D Canvas ”时,才会执行清理操作。我想通过单击 JButton 来制造“图形 2D Canvas ”被清理的错觉..

谢谢。

     addMouseListener(this);
addMouseMotionListener(this);
<小时/>
public void mousePressed(MouseEvent e) {
e.consume();
x1=e.getX();
y1=e.getY();
if(figure==1 || figure==3 ) {x2=x1; y2=y1;}
; }

PS:我不能使用机器人,因为我必须在每个操作系统上运行我的程序,有人告诉我我不能在每个程序上运行它:

Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

// SET THE MOUSE X Y POSITION
robot.mouseMove(65*Fond_noir.pourcent_largeur, 16*Fond_noir.pourcent_hauteur);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);

}

最佳答案

嗯,你对机器人的看法是对的。它依赖于平台,并且不能保证它将支持所有平台上的所有功能(来自 JavaDoc):

Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. For example, X-Window systems will throw the exception if the XTEST 2.2 standard extension is not supported (or not enabled) by the X server.

要模拟点击,您可以简单地执行以下操作:

JButton buttonToSimulateClicking = new JButton(...);
buttonToSimulateClicking.doClick(); // As simple as that !

如果您必须“以困难的方式”模拟单击,即模拟鼠标单击,您始终可以执行以下操作:

MouseEvent clickEvent = new MouseEvent(buttonToSimulateClicking, MouseEvent.MOUSE_CLICKED, ...);

EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.dispatchEvent(clickEvent);

关于java - 模拟鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23864439/

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