Search code examples
javamultithreadingloopsawtrobotinterruption

Having troubles making a second thread


I am trying to make a small programm which clicks the left mouse button in a certain intervall, for a certain time. The only problem I just can't solve is to be able to stop the loop whenever I want, even before the timer runs out. I have found out that one should run the loop in a worker thread, and that my stop button should interrupt that thread somehow, but I just can't manage it. I hope you can help me with some code.

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;     
import javax.swing.*;

public class KeyRepeater_v2 extends javax.swing.JFrame {

Robot robot;

boolean stop;
double time;
double time_milli;


public KeyRepeater_v2() throws AWTException {
    this.robot = new Robot();
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("Start");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Stop");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jLabel1.setText("Timer");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jLabel1))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(41, 41, 41)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        


private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    stop = true;
    //setFocusable (true);
    //JOptionPane.showMessageDialog(null, stop, "Test Titel", JOptionPane.OK_CANCEL_OPTION);
}                                        


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    stop = false;
    robot.delay(5000); //in milliseconds

    do {
            leftClick();
            robot.delay(1500);
            time_milli = time_milli - 1700;
    } while (time_milli > 0);

}                                        



private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    time = Double.parseDouble(jTextField1.getText()); 
    //System.out.print(time);
    time_milli = time * 1000;
}                                           




/**
 * @param args the command line arguments
 */
public static void main(String args[]) throws AWTException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(KeyRepeater_v2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(KeyRepeater_v2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(KeyRepeater_v2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(KeyRepeater_v2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        try {
            new KeyRepeater_v2().setVisible(true);
        } catch (AWTException ex) {
            Logger.getLogger(KeyRepeater_v2.class.getName()).log(Level.SEVERE, null, ex);
        }
    });

}


private void leftClick() {
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(100);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(100);
}


// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   

}

Quite some code was generated by netbeans... I don't really know how to make a new thread, and I don't know how to make my textfield (for the timer) and my buttons communicate with the thread either..... Really hope you can help me :D


Solution

  • I wanna thank everyone very much for taking time to give me tips. I have now solved my problem and will post my code, in case someone else encounters a similar problem. Each part is a separate java class. The timer is not very accurate, right now the mouseclicks are set about 2 seconds apart. The code may not be very elegant, but at least it works :D

    Brief summary of what it does:

    • interface with Textfield in order to specify the duration in seconds
    • start-button
    • stop-button

    After hitting the start-button the programme will wait 5 seconds, then perform left-mouse-click every two seconds, until the specified duration has passed or the user klicks the stop-button.

    Part 1 of 2:

    package Package_main;
    
    import java.awt.AWTException;
    import java.awt.event.ActionEvent;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    
    
    public class Main_Class extends javax.swing.JFrame {
    
        public static void main (String [] args) {
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main_Class().setVisible(true);
                }
            });
    
        }
    
    public Main_Class() {
        initComponents();
    } 
    
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    
    private void initComponents() {
    
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
    
        setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        setPreferredSize(new java.awt.Dimension(325, 106));
        setSize(getPreferredSize());
    
        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${VK_ESCAPE}"), this, org.jdesktop.beansbinding.BeanProperty.create("defaultCloseOperation"));
        bindingGroup.addBinding(binding);
    
        getContentPane().setLayout(new java.awt.GridBagLayout());
    
        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    jButton1ActionPerformed(evt);
                } catch (AWTException ex) {
                    Logger.getLogger(Main_Class.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 18, 11, 0);
        getContentPane().add(jButton1, gridBagConstraints);
    
        jButton2.setText("Stop");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 18, 11, 10);
        getContentPane().add(jButton2, gridBagConstraints);
    
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.ipadx = 131;
        gridBagConstraints.ipady = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(6, 10, 11, 0);
        getContentPane().add(jTextField1, gridBagConstraints);
    
        jLabel1.setText("Timer (in seconds)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 0);
        getContentPane().add(jLabel1, gridBagConstraints);
    
        bindingGroup.bind();
    
        pack();
    }
    
    double time;
    double time_milli;
    
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        time = Double.parseDouble(jTextField1.getText()); 
        System.out.println(time);
        time_milli = time * 1000;
    }                                           
    
    Worker_Thread wt;
    
    private void jButton1ActionPerformed(ActionEvent evt) throws AWTException {
        time = Double.parseDouble(jTextField1.getText()); 
        System.out.println(time);
        time_milli = time * 1000;
    
        wt = new Worker_Thread(time_milli);
        new Thread(wt).start();
    }
    
    private void jButton2ActionPerformed(ActionEvent evt) {
        wt.stop=true;
        System.out.println("stopped");
    }
    
    }
    

    Part 2 of 2 (worker thread):

    package Package_main;
    
    import java.awt.AWTException;
    import java.awt.Robot;
    import java.awt.event.InputEvent;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Worker_Thread extends Thread {
    
    volatile boolean stop;
    double time_milli;
    
    Robot robot;
    
    public Worker_Thread (double t) {
        time_milli = t;
    }
    
    public void run() {
    
            try {
                this.robot = new Robot();
            } catch (AWTException ex) {
                Logger.getLogger(Worker_Thread.class.getName()).log(Level.SEVERE, null, ex);
            }
            stop = false;
            robot.delay(5000); //in milliseconds
    
            do {
                leftClick();
                robot.delay(1800);
                time_milli = time_milli - 2000;
                System.out.println(time_milli);
    
            } while (time_milli > 0 && (!stop));    
    
    }
    
    private void leftClick() {
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.delay(100);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        robot.delay(100);    
    
    }
    
    }