I am looking to create an autoclicker with a JFrame GUI in Java with the Robot class. I was wondering if this is the best way to create the GUI in different threads so that it would remain responsive even while the autoclicker/robot is performing actions?
I read in the Oracle documentation that Swing objects have their own Event Dispatcher Thread, so maybe this isn't necessary at all? If so, what is it? Thanks in advance!
package Engine;
import javax.swing.*;
import GUI.UI;
public class Engine {
private Thread UIthread, clickerThread;
public UI ui;
public AutoClicker autoClicker;
public Engine(int width, int height) {
ui = new UI(width, height);
ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ui.setVisible(true);
UIthread = new Thread(ui);
UIthread.start();
//autoclicker is where the Robot class
autoClicker = new AutoClicker();
clickerThread = new Thread(autoClicker);
clickerThread.start();
}
}
Here's the UI(and its event handler) and AutoClicker classes respectively in case it helps:
package GUI;
import javax.swing.*;
public class UI extends JFrame implements Runnable{
public int width, height;
JButton start, stop;
public UI(int width, int height) {
this.width = width;
this.height = height;
this.setLayout(null);
this.setSize(width, height);
}
public void init() {
start = new JButton();
start.setText("start");
start.setBounds(100, 100, 100, 30);
add(start);
stop = new JButton();
stop.setText("stop");
stop.setBounds(100, 140, 100, 30);
add(stop);
EventHandler eHandler = new EventHandler(this);
start.addActionListener(eHandler);
stop.addActionListener(eHandler);
}
@Override
public void run() {
init();
}
}
EventHandler class
package GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventHandler implements ActionListener{
private UI ui;
public EventHandler(UI ui) {
this.ui = ui;
}
public void actionPerformed(ActionEvent actionEvent) {
if(actionEvent.getSource().equals(ui.start)) {
//start autoclicking
System.out.println("start");
}else if(actionEvent.getSource().equals(ui.stop)) {
//stop autoclicking
System.out.println("stop");
}
}
}
The autoclicker class:
package Engine;
import java.awt.AWTException;
import java.awt.Robot;
public class AutoClicker implements Runnable{
private Robot robot;
public void run() {
try {
robot = new Robot();
//do mouse clicks and stuff
} catch (AWTException e) {
e.printStackTrace();
}
}
}