How do I keep my Stop Button listening during while loop?

Viewed 45

I'm new to Java and am trying to create an application for autoclicking/keypressing. The basic functions of the app are working... It takes input from a JComboBox and then chooses which method to run, space(); or click();.

However, when it gets to the runIt(); I cannot escape that loop, meaning I cannot click the stop button (btnStop) to get running = false to stop the loop.

What might I be missing?

        btnStart = new JButton("Start");
        btnStart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                try {
                    setup();
                }
                catch(AWTException e1) {
                    txtError = "Something's wrong. I can feel it.";
                    errMessage.setText(txtError);
                }
            }
        });
        btnStart.setBounds(35, 69, 89, 23);
        getContentPane().add(btnStart);

        btnStop = new JButton("Stop");
        btnStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                running = false;
            }
        });
        btnStop.setBounds(35, 99, 89, 23);
        getContentPane().add(btnStop);

        errMessage = new JLabel("Error Messages show up here.");
        errMessage.setHorizontalAlignment(SwingConstants.CENTER);
        errMessage.setBounds(35, 152, 377, 14);
        getContentPane().add(errMessage);
    }


    public void runIt() throws AWTException {
        running = true;
        while (running)
            if (entKey == "Space")
                space();
            else
                click();
    }

    private void setup() throws AWTException{
        entKey = keySelected.getSelectedItem().toString();
        strDelay = txtDelay.getText();

        try {
            intDelay = Integer.parseInt(strDelay);
        }
        catch(Exception g) {
            txtError = "Please enter a valid integer";
            errMessage.setText(txtError);
        }
        finally {
            intDelay = Integer.parseInt(strDelay);
            runIt();
        }

    }

    private void space() throws AWTException{
        btnStart.setVisible(false);
        Robot robot = new Robot();
        robot.delay(intDelay);
        robot.keyPress(KeyEvent.VK_SPACE);

    }

    private void click() throws AWTException{
        btnStart.setVisible(false);
        Robot robot = new Robot();
        robot.delay(intDelay);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.delay(100);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

    }
0 Answers
Related