そこで、ランダムなキーストロークを送信するという意図された目的を実行するプログラムを作成しました。これで、開始/停止ボタンを備えた非常に基本的な 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 が変数を更新していないことです。なんで?私は本当に混乱しています。
読んでくれてありがとう。