我正在尝试编写一个程序,每3分钟移动一次鼠标(停止屏幕保护程序启动),但我希望能够随意停止并启动它。正如您在下面看到的,我已经创建了按钮和方法,但是当您单击运行时,它会进入while循环,因为它实际上是一个无限循环,它将无法查看您是否单击了结束按钮。
我在点击结束按钮时尝试了system.exit(0),将结束按钮传入false方法run(),你可以从代码中看到我在while循环中尝试了if语句看看它是否会引起我的注意!
非常感谢任何帮助!
代码:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test
{
boolean loop;
static boolean exit;
public static void main(String[] args) throws AWTException
{
System.out.println("before");
makeButtons();
System.out.println("after");
}
public static void makeButtons()
{
JFrame jfrMain = new JFrame ("Mouse Robot");
JPanel jplMain = new JPanel();
final JButton run = new JButton("Run");
final JButton end = new JButton("End");
run.setEnabled(true);
end.setEnabled(true);
run.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//run.setEnabled(false);
//end.setEnabled(true);
try {
run(true);
} catch (AWTException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
end.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exit = true;
}
});
jplMain.setLayout(new FlowLayout());
jplMain.add(run);
jplMain.add(end);
jfrMain.getContentPane().add(jplMain, BorderLayout.CENTER);
jfrMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrMain.pack();
jfrMain.setVisible(true);
}
public static void run(boolean loop) throws AWTException
{
Robot r2d2 = new Robot();
while(loop)
{
System.out.println("1");
Point mousePoint = MouseInfo.getPointerInfo().getLocation();
mousePoint.translate(0, 1);
r2d2.mouseMove(mousePoint.x, mousePoint.y);
r2d2.delay(60000);
//r2d2.delay(60000);
//r2d2.delay(60000);
System.out.println("2");
mousePoint = MouseInfo.getPointerInfo().getLocation();
mousePoint.translate(0, -1);
r2d2.mouseMove(mousePoint.x, mousePoint.y);
r2d2.delay(60000);
//r2d2.delay(60000);
//r2d2.delay(60000);
System.out.println("looping");
if (exit = true)
{
break;
}
}
}
}
答案 0 :(得分:1)
尝试
if (exit == true)
{
break;
}
答案 1 :(得分:1)
首先纠正退出的条件,即如第一个答案中所述,使其成为exit == true
。
其次我不认为这会解决你的问题,因为你在actionPerformed中进行了一个无限循环,它被EDT(甚至Dispatch Thread)调用,这将完全停止事件处理。因此,在actionPerformed方法中启动一个新的Thread来移动鼠标。保持对该线程的引用,以便您可以停止/中断线程,或者您也可以设置退出条件以停止线程。
如果你需要一个代码示例,请告诉我。
答案 2 :(得分:0)
if(exit == true) { 打破; }
答案 3 :(得分:0)
我对此有所怀疑,但我还没有尝试过。如果没有听过鼠标,Java会不会运行,这最终会成为无限循环?
我认为只需按一下javascript函数setInterval()
就可以移动鼠标,并在点击按钮后移动clearInterval()
。
答案 4 :(得分:0)
首先使它成为exit == true;
而不是使用exit = true;
,您可以使用loop = false
。
单击结束按钮后,它仍然不会在循环时停止。 要在单击按钮后立即停止它,您必须使用两个不同的线程。 1.处理你的活动。 2.另一个运行while循环。
在事件处理线程中,您必须维护while循环线程的对象,通过该对象可以设置loop
或exit
变量的适当值以停止循环。