Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By Fubarable

Thread: Auto Clicking Application

  1. #1
    dpedroia15 is offline Member
    Join Date
    Mar 2010
    Posts
    9
    Rep Power
    0

    Default Auto Clicking Application

    Hey, I could really use some help with this application I'm trying to make (new to Java).

    I followed the Swing Tutorial with Netbeans very closely, yet when I run the application, a GUI doesn't even show up.

    If someone could look at the code (it's pretty short) and see why I can't seem to get the GUI working, I'd be grateful. You don't have to look at the actual logic of the program (to see if it would work when I get the GUI working), but if you could, it would help immensely :)

    Here's the source:

    Java Code:
    /*
     * TheClicker.java
     *
     * Created on Mar 1, 2010, 6:11:31 PM
     */
    
    package learn;
    
    import java.awt.Robot;
    
    /**
     *
     * @author Matt
     */
    public class TheClicker extends javax.swing.JFrame {
    
        /** Creates new form TheClicker */
        public TheClicker() {
            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() {
    
            jTextField1 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jToggleButton1 = new javax.swing.JToggleButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("The Clicker");
    
            jTextField1.setText("100");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jLabel1.setText("ms");
    
            jToggleButton1.setText("Start");
            jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jToggleButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jToggleButton1)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jToggleButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            if (clicked == true) {
    		clicked = false;
    	}
    	else {
    		clicked = true;
    	}
        }
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
            msS = jTextField1.getText();
        }
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TheClicker().setVisible(true);
                }
            });
            while(clicked == true) {
        		clicking();
            }
        }
    
    private static void clicking() {
    	ms = new Integer(Integer.parseInt(msS));
            try {
                Robot mouseClick = new Robot();
                while (clicked == true) {
    		mouseClick.mousePress(1);
    		mouseClick.wait(ms);
    		mouseClick.mouseRelease(1);
                }
            }
            catch (Exception e){}
    }
        private static int ms;
        private static String msS;
        private static boolean clicked;
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JToggleButton jToggleButton1;
        // End of variables declaration
    
    }
    Thanks

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    What is this code supposed to do? It never enters the while loop since clicked is false, and if it did all you would do would be generate an error from trying to read a String that's null.

    I see several other significant problems with your code including an infinite while loop that if it worked would freeze your GUI as well as a bunch of unnecessary use of static variables and methods. Then there's the empty catch block...

    You may wish to go through the basic Java tutorials before trying GUI programming. It will make your GUI programming experience much more rewarding and less frustrating.

    Much luck.
    Last edited by Fubarable; 03-02-2010 at 01:19 AM.

  3. #3
    dpedroia15 is offline Member
    Join Date
    Mar 2010
    Posts
    9
    Rep Power
    0

    Default

    Thanks for the feedback.

    Well boolean clicked is supposed to be true once the user click the JButton, and they can click it again to stop it. It's supposed to click the mouse at whatever interval the user enters.

    Wouldn't the GUI pop up before it even considers the while loop?

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by dpedroia15 View Post
    Thanks for the feedback.

    Well boolean clicked is supposed to be true once the user click the JButton,
    Nope. Your code considers the while loop, rejects it, and considers it no more. It's just doing what you wrote it to do.


    and they can click it again to stop it. It's supposed to click the mouse at whatever interval the user enters.
    If you code did work as you wanted it to, that while(true) would freeze your app, and the user would never be able to stop it.

    Wouldn't the GUI pop up before it even considers the while loop?
    Nope. You may want to read the Swing tutorials (not the netbeans version) to get a handle on event-driven programming.

    Follow the logic please:

    Java Code:
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            // Your Swing GUI has been set in motion in its own thread
            new TheClicker().setVisible(true);
          }
        });
    
        // meanwhile the main thread comes here, sees that clicked is false
        // and then skips over this while loop
        while (clicked == true) {  // better to do while (clicked) {...
          clicking();
        }
    
        // and once the while loop has been skipped over, it will never 
        // be approached again
      }

  5. #5
    dpedroia15 is offline Member
    Join Date
    Mar 2010
    Posts
    9
    Rep Power
    0

    Default

    Ok, thanks again for helping out.

    So to clarify, you're saying that the GUI won't pop up because it tries to execute the while loop simultaneously with the gui's startup, and since it fails to do the loop, the program ends and the GUI never shows?

    I'm guessing I'd better use an if statement...

    Java Code:
    /*
     * TheClicker.java
     *
     * Created on Mar 1, 2010, 6:11:31 PM
     */
    
    package learn;
    
    import java.awt.Robot;
    
    /**
     *
     * @author Matt
     */
    public class TheClicker extends javax.swing.JFrame {
    
        /** Creates new form TheClicker */
        public TheClicker() {
            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() {
    
            jTextField1 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jToggleButton1 = new javax.swing.JToggleButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("The Clicker");
    
            jTextField1.setText("100");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jLabel1.setText("ms");
    
            jToggleButton1.setText("Start");
            jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jToggleButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(18, 18, 18)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jToggleButton1)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jToggleButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
            if (clicked == true) {
    		clicked = false;
    	}
    	else {
    		clicked = true;
    	}
        }                                              
    
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
            msS = jTextField1.getText();
        }                                           
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TheClicker().setVisible(true);
                }
            });
            try {
                while(clicked){
                    clicking();
                }
                if(!clicked){
                    return;
                }
            }
            catch (Exception e) {}
        }
    
    private static void clicking() {
    	ms = new Integer(Integer.parseInt(msS));
            try {
                Robot mouseClick = new Robot();
                mouseClick.mousePress(1);
                mouseClick.wait(ms);
                mouseClick.mouseRelease(1);
            }
            catch (Exception e){}
    }
        private static int ms;
        private static String msS;
        private static boolean clicked;
        // Variables declaration - do not modify                     
        private javax.swing.JLabel jLabel1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JToggleButton jToggleButton1;
        // End of variables declaration                   
    
    }
    New, only a few changes, and no change to the result
    Last edited by dpedroia15; 03-02-2010 at 03:13 AM.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I'm still not sure what your program is supposed to be doing? Is the mouse supposed to be continually clicking where ever it is currently located?

    Why not try something that is easier to see? How about a JLabel that changes color when the toggle button is selected and stops when not?

    OK, let's to through some of your code, shall we?
    Java Code:
      private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        if (clicked == true) {
          clicked = false;
        } else {
          clicked = true;
        }
      }
    again, since clicked is a boolean, it's cleaner to do if (clicked) rather than if (clicked == true). Also, you run a much lower risk of doing the pernicious error of if (clicked = true). But even this is unnecessary. If all you want to do is toggle clicked, all you need to do is
    Java Code:
      private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        clicked = !clicked; // clicked becomes NOT clicked, the opposite boolean value
      }
    But regardless of whether you use your code or my code, please understand that all that happens when you push the button is that clicked toggles from true to false and visa versa. Nothing else happens. The JTextField is never read, no robot is initiated, nothing? Why because if you want anything to happen on button click, you must call it in the button ActionListener's actionPerformed method.

    Here
    Java Code:
      private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        msS = jTextField1.getText();
      }
    You change msS String, but only if enter is pressed in the JTextField since this is called in the JTextField ActionListener's actionPerformed method. Again, this will not be read when the button is clicked since it's not in the button ActionListener's actionPerformed method. So if someone changes the text field's text, does not press enter, but then clicks the button, the msS string will not change.

    This code
    Java Code:
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TheClicker().setVisible(true);
          }
        });
        try {
          while (clicked) {
            clicking();
          }
          if (!clicked) {
            return;
          }
    has the exact same problem that I outlined in my previous post. Again, if this were successful at doing what you wanted, the clicking method would continually be called, creating thousands of Robot objects, overwhelming the JVM and cause your program to crash. Before that happened though, the while (true) portion would hog Swing's main thread, the event dispatch thread (EDT) causing your program to be unresponsive and helpless as the inevitable heap overload and program crash approached.

    This:
    Java Code:
        } catch (Exception e) {
        }
    Should never be done unless you really really know what you're doing. You are ignoring all exceptions, and so if a run-time error occurs, you'll never know why it's occuring. Simply don't do this. At least have an e.printStackTrace() inside of the exception block.

    This:
    Java Code:
      private static void clicking() {
        ms = new Integer(Integer.parseInt(msS));
        try {
          Robot mouseClick = new Robot();
          mouseClick.mousePress(1);
          mouseClick.wait(ms);
          mouseClick.mouseRelease(1);
        } catch (Exception e) {
        }
      }
    is a static method, and there should be no static methods or variables in this type of program (other than the main method and its closely associated methods). Also, calling wait on the Robot and on the EDT is not a good thing.

    Here:
    Java Code:
      private static int ms;
      private static String msS;
      private static boolean clicked;
    is again unnecessary static variables. Using these without reason will hamper class's ability to create objects with independent states.


    _________________

    Here's an example of a label flashing program that has a similar thrust as your program, but is different (it works for one):
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class TheClicker2 {
      private static final Color[] COLORS = {
        Color.red, Color.orange, 
        Color.yellow, Color.green, 
        Color.blue, Color.magenta};
      private static final String START = "Start";
      private static final String STOP = "Stop";
      private JPanel mainPanel = new JPanel();
      private JLabel flashLabel = new JLabel("Flashing Label");
      private JTextField flashTimeField = new JTextField("200", 10);
      private JToggleButton startBtn = new JToggleButton(START);
      private Timer timer;
      private int colorIndex = 0;
    
      public TheClicker2() {
        // make flashlabel big
        flashLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 32));
        flashLabel.setForeground(COLORS[0]);
        startBtn.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            startBtnActionPerformed();
          }
        });
        
        JPanel southPanel = new JPanel();
        southPanel.add(flashTimeField);
        southPanel.add(new JLabel("ms"));
        southPanel.add(startBtn);
        
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(flashLabel, BorderLayout.CENTER);
        mainPanel.add(southPanel, BorderLayout.SOUTH);
      }
    
      private void startBtnActionPerformed() {
        if (startBtn.isSelected()) {
          startBtn.setText(STOP);
          try {
            int ms = Integer.parseInt(flashTimeField.getText());
            timer = new Timer(ms, new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                timerActionPerformed();
              }
            });
            timer.start();
          } catch (NumberFormatException e) {
            flashTimeField.setText("");
            JOptionPane.showMessageDialog(mainPanel, "Only enter whole numbers", 
                "Non-Numeric Data Error", JOptionPane.ERROR_MESSAGE);
          }
        } else {
          startBtn.setText(START);
          if (timer != null && timer.isRunning()) {
            timer.stop();
            timer = null;
          }
        }
      }
    
      private void timerActionPerformed() {
        colorIndex++;
        colorIndex %= COLORS.length;
        flashLabel.setForeground(COLORS[colorIndex]);
      }
    
      public JPanel getMainPanel() {
        return mainPanel;
      }
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("TheClicker2");
        frame.getContentPane().add(new TheClicker2().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
          }
        });
      }
    }
    Probably the biggest difference is mine has a lot more code in my button's actionPerformed method. Inside I create a Swing Timer that will flash the JLabel at the rate set by the JTextField.

  7. #7
    dpedroia15 is offline Member
    Join Date
    Mar 2010
    Posts
    9
    Rep Power
    0

    Default

    Ok, thank you for all of the time you spent answering my query.

    I will take your advice and look back into the tutorials to see what I need to brush up on.

    ++rep

    Thanks again!

Similar Threads

  1. Double-clicking .jar files?
    By StokedOnMe in forum New To Java
    Replies: 11
    Last Post: Yesterday, 12:52 PM
  2. How to auto start Java application form browser
    By marcinz in forum New To Java
    Replies: 5
    Last Post: 04-03-2011, 05:30 PM
  3. Auto contrast and auto brightness
    By oxxxis in forum Java 2D
    Replies: 0
    Last Post: 01-21-2010, 08:32 PM
  4. Auto-complete/Auto-fix for custom statement
    By dark_cybernetics in forum Eclipse
    Replies: 0
    Last Post: 08-19-2008, 11:19 AM
  5. Java3D: Clicking and getting coordinates?
    By seabhcan in forum Advanced Java
    Replies: 0
    Last Post: 01-11-2008, 02:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •