#Override
public void keyPressed(KeyEvent e) {
if ( e.getKeyChar() == 'x' ) {
Clicking = true;
}
try {
if(Clicking == true)
robot = new Robot();
while (true) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
if(e.getKeyChar() == 'b'){
Clicking = false;
}
} } catch(AWTException awtException) {
awtException.printStackTrace();
}
}
I'm trying to make it so whenever I press b the autoclicker stops it works when I press x but doesn't stop after I press b
You are using the mechanism on the core while, I don't say it is bad, although what about assigning it to methods like run_it and stop_it? Or just, perform_the_click (that cud be more simply).
"I'm trying to make it so whenever I press b the autoclicker stops it works when I press x but doesn't stop after I press b".
I seriously don't see it has sense, try using commas, thus it makes it non-understandable for the community.
Please show more about the project, where does the Clicking just came from?
You require another thread to listen to your 'b's click. Because it is running on the current thread it blocks listening to inputs.
An idea of something like this:
if(e.getKeyChar() == 'x' ) {
if(robot == null) {
robot = new Robot(someObjectIWantToBringOver);
Thread thread = new Thread(robot);
thread.start();
}
}
if(e.getKeyChar() == 'b' ) {
if(robot != null) {
robot.stop();
robot = null;
}
}
//In your Robot class
class Robot implements Runnable {
private volatile boolean running = true;
private final Object xyz;
public Robot(Object abc??) {
this.xyz = abc;
}
...
public void run() {
while(running) {
try{
xyz.mousePress(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(1000);
xyz.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}catch(Exception e) {}
}
}
public void stop() {
running = false;
}
}
Looks like a fun project. Have fun!
Related
I'm trying to break loop using AWTEventListener, but in 'if' after checking if I pressed ctrl+p it says error by the break;
try {
Robot robot = new Robot();
int z = 0;
while(true) {
robot.mouseMove(x + z, y);
z++;
AWTEventListener listener = new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
try {
KeyEvent evt = (KeyEvent)event;
if(evt.getID() == KeyEvent.KEY_PRESSED && evt.getModifiers() == KeyEvent.CTRL_MASK && evt.getKeyCode() == KeyEvent.VK_P) {
break; //ERROR
}
}
catch(Exception e) {
e.printStackTrace();
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
}
} catch (AWTException e) {
}
I don't think you understand what you're doing when creating the listeners. You're basically creating a class right in place, and that class has a method named eventDispatched(). There's no loop inside eventDispatched(), so there's no loop to break out of.
Furthermore, it's probably a mistake to assume the event is a KeyEvent. That's a side note.
Your listener probably needs to set some field that your while loop is looking at. Instead of while(true) you need to do "while(my listener hasn't set some flag to another value)".
volatile private boolean mouseDown = false;
private int max = 0;
private int min = 0;
private Robot robot;
public MouseClickListener()
{
try
{
robot = new Robot();
} catch (AWTException e)
{
e.printStackTrace();
}
}
#Override
public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent)
{
}
#Override
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent)
{
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
max = Native.get().getFrame().getCps().getValue() + Native.get().getFrame().getDev().getValue();
min = Native.get().getFrame().getCps().getValue() - Native.get().getFrame().getDev().getValue();
mouseDown = true;
initThread();
}
}
#Override
public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent)
{
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
mouseDown = false;
}
}
Hi there, so basically I'm trying to make an auto clicker which clicks at values to a JSlider (a random value between say 9 and 13, just for example).
So on mouse click the initThread method is called, and the clicks per second is worked out ( a random number between the JSlider value, which is from a diff. class), and then from that, I click and then sleep the thread for 1 / randomNum (in seconds) so that it clicks that many times per second.
For some reason it's clicking at like 200cps and lagging my computer out. Does anyone see any problem with my code?
Thanks.
NEW CODE FOR CLICKER;
public class ClickMethod implements Runnable
{
#Override
public void run()
{
System.out.println("STARTED");
do
{
System.out.println("RUNNING");
Random r = new Random();
int random = r.nextInt((max - min) + 1) + min;
robot.mousePress(BUTTON1_MASK);
robot.mouseRelease(BUTTON1_MASK);
try
{
Thread.sleep(1000 / random);
} catch (InterruptedException e)
{
e.printStackTrace();
}
} while (mouseDown);
}
}
For some reason this only runs once and then isn't called when the mouseDown variable changes.
If this is intended to be clicked by you every so often then it creates numerous threads which all click away
public void nativeMousePressed(NativeMouseEvent nativeMouseEvent)
{
if (nativeMouseEvent.getButton() == NativeMouseEvent.BUTTON1)
{
max = Native.get().getFrame().getCps().getValue() + Native.get().getFrame().getDev().getValue();
min = Native.get().getFrame().getCps().getValue() - Native.get().getFrame().getDev().getValue();
mouseDown = true;
initThread();
}
}
You need to remove initThread() from there and call it once somewhere , e.g., in the constructor.
I'm trying to learn Threads in Swing.
I have a Frame with a JProgressBar (progress), five JButtons (Start, Suspend, Resume, Cancel, Close), and a JLabel (label1).
The frame opens. Only Start is enabled. Start calls my class Progressor:
Updated Again Once and For All
Progressor progressor; //declared as class variable, initialized new in constructor and again in overridden done method
Here's the ButtonListener class:
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbStart) {
progressor.execute();
label1.setText("Progressing ...");
jbCancel.setEnabled(true);
jbResume.setEnabled(true);
jbSuspend.setEnabled(true);
jbClose.setEnabled(true);
}
if(e.getSource() == jbCancel) {
progressor.cancel(true);
label1.setText("Progress Canceled");
}
if (e.getSource() == jbSuspend) {
label1.setText(progressor.suspendProgress());
}
if (e.getSource() == jbResume) {
label1.setText(progressor.resumeProgress());
}
if (e.getSource() == jbClose) {
dispose();
}
}
}//buttonlistener
Here's the SwingWorker class:
public class Progressor extends SwingWorker<Void, Integer> {
private volatile boolean suspend = false;
private Object lock = new Object();
#Override
protected Void doInBackground() {
for (int i = 0; i <= 10; i++) {
checkForSuspend();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
publish(i);
}
return null;
}
#Override
protected void process(List<Integer> list) {
int value = list.get(list.size() - 1);
progress.setValue(value);
}
public void checkForSuspend() {
synchronized (lock) {
while (suspend) {
try {
lock.wait();
} catch (InterruptedException ie){
}
}
}
}//checkForSuspend
#Override
protected void done() {
label1.setText("All Done. Press close to exit");
progressor = new Progressor();
}
public synchronized String suspendProgress() {
suspend = true;
return "Progress suspended ...";
}
public synchronized String resumeProgress() {
synchronized (lock) {
suspend = false;
lock.notify();
return "Progress resumed ...";
}
}
}//Progressor class
Everything works except the cancel doesn't doesn't actually cancel the thread (the progress bar continues).
Should I suspend it before canceling?
This How to Pause and Resume a Thread in Java from another Thread question looks very similar to yours and has some nice examples in the answers.
As for your own code and why it does not work:
You create a new progressor on every click. You should be using and controlling one, instead of creating new ones every time.
When suspending your progressor finishes work instead of suspending. As the above question states - you should be looking at the flag at some points of your computation and acting on it. Example:
while (!cancel) {
if (!suspended) {
for (int i = 1; i <= 10; i++) {
Thread.sleep(1000);
publish(i);
}
}
}
The above code will suspend when it next reaches 10 (unless you resumed it before that), and finish when you press cancel (Cancel needs to be added as an extra flag in the obvious manner).
Your thread should run inside a while loop that looks for a boolean to change value from another object, then simply change the state with setPause(true/false) when you click the button:
while(true){
if(object_everyone_can_reference.getPause()){
Thread.sleep(1000);
}
}
The default close shortcut (Cmd+q on Mac) doesn't work on this program i coded in java, do you know why?
I am an absolute beginner and would be glad if you helped me!
The code:
public static void main(String[] args) throws IOException, AWTException{
final Robot robot = new Robot();
robot.delay(2000);
while(true)
{
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(50);
}
}
}
}
That would be because Java is trying to be as cross-platform (or platform-independent) as it can be. You could make your own closing shortcut, using the Key class explained in your previous questions (specifically: How to cast a keyboard event). However, I don't think you could detect mac-specific keys, unless you dive into JNI (Java Native Interface), but if you are a beginner I wouldn't recommend it just yet.
For example, say you would like the shortcut to be CTRL+Q. Add another field in your Key class:
private boolean ctrlPressed = false;
Then, make a pressing check:
#Override
public void keyPressed(KeyEvent e)
{
//Previous code
if(e.getKeyCode() == KeyEvent.VK_CONTROL)
{
ctrlPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e)
{
//Previous code
if(e.getKeyCode() == KeyEvent.VK_CONTROL)
{
ctrlPressed = false;
}
}
And finally, the Q part:
#Override
public void keyTyped(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_Q && ctrlPressed)
System.exit(0);
}
Using Jinput and Java in Netbeans, I'm working on a very small project that simply Pops up a JFrame alarm window when lets say a user presses down on the 'K' on the keyboard and terminates the JFrame alarm window when the user lets go of 'k'. In my code, I seemed to get stuck in the while loop as the JFrame opened on the first press down and couldn't seem to close. I researched and I found that using javax.swing.Timer was the better way to do it. However, since I'm a newbie at this, all the different ways to use timer just made me even more confused. Could someone please see my code and point me in the right direction?
Here is my code;
public void startPolling() {
while(true) {
ControllerEnvironment.getDefaultEnvironment().getControllers();
ca[index].poll();
EventQueue queue = ca[index].getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
StringBuffer buffer = new StringBuffer(ca[index].getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
buffer.append(value);
} else {
if(value==1.0f) {
buffer.append("On");
if ("K".equals(comp.getName())){
alarmBox();
}
} else {
buffer.append("Off");
if ("K".equals(comp.getName())){
alarmBox.setVisible(false);
}
}
}
System.out.println(buffer.toString());
}
}
}
alarmBox() is my JFrame.
I was working on it and here is my updated code:
public void startPolling() {
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
ca[index].poll();
EventQueue queue = ca[index].getEventQueue();
Event event = new Event();
while(queue.getNextEvent(event)) {
StringBuffer buffer = new StringBuffer(ca[index].getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
if(comp.isAnalog()) {
buffer.append(value);
} else {
if(value==1.0f) {
buffer.append("On");
if ("K".equals(comp.getName())){
alarmBox();
}
} else {
buffer.append("Off");
if ("K".equals(comp.getName())){
alarmBox.dispose();
}
}
}
System.out.println(buffer.toString());
}
try {
Thread.sleep(20);
} catch (InterruptedException f) {
f.printStackTrace();
}
}
}); timer.start();
if you just want to open and close window,y to use timer?
you have a very complicated code,for a simple task.
you can add a ComponentListener to your JFrame to hide,somthing like this:
frame.addComponentListener(new ComponentAdapter(){
public void componentMoved(ComponentEvent e) {
if (popup.isVisible()){
popup.setVisible(false);
}
}
});