所以我创建了一个程序,它的目的是发送随机击键。现在我已经实现了一个带有开始/停止按钮的非常基本的 GUI。该程序是在整数“running”等于1时运行的。所以我决定让按钮将running的值从0更改为1,开始循环。
这是代码:
public class AutoKeyboard extends JFrame {
public static int running = 0; // program will not run until this is 1
Random r = new Random();
public static int randInt(int min, int max) { // returns random number
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
private JLabel label;
private JButton button;
public AutoKeyboard() {
setLayout(new FlowLayout());
label = new JLabel("Not Running");
add(label);
button = new JButton("Start");
add(button);
event f = new event();
button.addActionListener(f);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent f) {
label.setText("Running");
System.out.println("Running");
running = 1; // changes running to 1? but doesn't start the program?
}
}
public static void main(String[] args) throws InterruptedException {
AutoKeyboard gui = new AutoKeyboard();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(180, 80);
gui.setVisible(true);
gui.setResizable(false);
gui.setTitle("Anti AFK");
while (running == 1) { // if running is 1, do this
try {
int delay = randInt(4864,7834); // 336415, 783410 15 97
Robot robot = new Robot();
int keypress = randInt(65, 86);
Thread.sleep(delay);
robot.keyPress(keypress);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
}
我的问题是,每当我按下我的 JButton“开始”时,它似乎并没有将 int running 更改为 1,并且程序没有启动。每当我在代码中手动更改 int 时,程序都会运行。所以问题是 JButton 没有更新变量。为什么?我真的很困惑。
感谢大家阅读。