制作第二个线程时遇到问题

Having troubles making a second thread

我正在尝试制作一个小程序,它可以在一定的时间间隔内单击鼠标左键一段时间。我无法解决的唯一问题是能够随时停止循环,甚至在计时器 运行 结束之前。我发现应该 运行 工作线程中的循环,并且我的停止按钮应该以某种方式中断该线程,但我无法管理它。我希望你能帮我写一些代码。

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                   

}

netbeans 生成了相当多的代码... 我真的不知道如何创建一个新线程,我也不知道如何让我的文本字段(用于计时器)和我的按钮与线程通信......真的希望你能帮助我:D

您肯定想看看计时器。基本上,它是为了方便您使用线程。我不想修改太多你的代码,所以我给你提供了一个示例来替换你正在使用的 do while 循环(它来自官方 Timer's javadoc)。

ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                do {
                    System.out.println("left click");
                    leftClick();
                    robot.delay(1500);
                    time_milli = time_milli - 1700;
                } while (time_milli > 0);
            } 
        };
        new Timer(5000, taskPerformer).start();

请注意,我明确地留下了控制台打印,以检查是否每 5 秒执行一次操作就会调用您;当您单击更加用户友好的开始按钮时,计时器还可以防止您的 GUI 被冻结。

非常感谢大家花时间给我提示。我现在已经解决了我的问题并将 post 我的代码,以防其他人遇到类似的问题。每个部分都是一个单独的 java class。计时器不是很准确,现在鼠标点击间隔大约 2 秒。代码可能不是很优雅,但至少可以工作:D

它的作用的简要总结:

  • 与 Textfield 的接口以指定持续时间(以秒为单位)
  • 开始按钮
  • 停止按钮

点击开始按钮后,程序将等待 5 秒,然后每两秒执行一次鼠标左键单击,直到指定的持续时间过去或用户点击停止按钮。

第 1 部分,共 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");
}

}

第 2 部分(共 2 部分)(工作线程):

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);    

}

}