1
timer.schedule(new PressTask(), 2000, rand);
我希望上面的rand在每次執行時都是不同的數字。例如,第一次計時器。 時間表被稱爲,比方說蘭特是5345.下一次它被調用時,它應該是一個不同的數字,而不是5345.我該怎麼做?如何在每次運行TimerTask時使timer.schedule()的週期發生變化?
對不起,這只是我爲自己做的一點練習。
public class Keypress
{
static Timer timer = new Timer();
static JFrame frame = new JFrame();
static JButton btn = new JButton("start");
static JButton btn2 = new JButton("stop");
static JTextField txt = new JTextField();
static Robot robot;
static Random couch = new Random();
static int rand = couch.nextInt(10000 - 5000) + 5000;
public static void main(String[] args)
{
System.out.println(rand);
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.addActionListener(new startPress());
btn2.addActionListener(new stopPress());
frame.setLayout(new GridLayout(3, 1));
frame.add(btn);
frame.add(btn2);
frame.add(txt);
try
{
robot = new Robot();
}
catch (AWTException e)
{
e.printStackTrace();
}
frame.setVisible(true);
}
static class startPress implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
timer.schedule(new PressTask(), 2000, rand);
}
}
public static class PressTask extends TimerTask
{
public void run()
{
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
}
}
static class stopPress implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
這可能是你的答案:[http://stackoverflow.com/questions/8386545/java-timer-with-not-fixed-delay](http://stackoverflow.com/questions/8386545/java-timer -with-not-fixed-delay) – downeyt
你的代碼每次運行時都會給rand一個不同的數字 –
@downeyt謝謝,這解決了這個問題。 – Zerukai