制造第二个线程时遇到麻烦

时间:2015-04-24 20:49:44

标签: java multithreading loops awtrobot interruption

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

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

2 个答案:

答案 0 :(得分:1)

you definitely want to look at timers. Basically, it's here to facilitate you the usage of threading. I didn't want to modify too much your code so I provide you a sample that replaces the do while loop you were using (it's from the official 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();

Please note that I explicitely left the console print for you to check that you are called on action performed every 5 secondes ; also Timers keeps your GUI from being freezed when you click on the start button which is more user-friendly.

答案 1 :(得分:0)

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

简要概述:

  • 与Textfield接口以指定持续时间(秒)
  • 启动按钮
  • 停止按钮

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

第1部分:

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部分(工作人员主题):

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

}

}
相关问题