Niral Mehta
Niral Mehta

Reputation: 63

Increment an integer in a JTextField by one

I am trying to increment the value of a JTextfield (tenSecs) by one for every instance that my other JTextfield (oneSecs) reaches 0. I am having difficulty trying to increase the value of my tenSecs JTextfield as it is always 0. When manually changing the number, as soon as oneSecs reaches 0, tenSecs reverts to 0.

javax.swing.Timer tm = new javax.swing.Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        AddOneActionPerformed(evt);
    } 
});

private void StartStopTimerActionPerformed(java.awt.event.ActionEvent evt) {                                               

    if (!tm.isRunning()) {
        tm.start();
    } else {
        tm.stop();
    }

    ScheduledExecutorService e= Executors.newSingleThreadScheduledExecutor(); //Start new scheduled executor service to invoke a timer that start wehn button is pressed
    e.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            //Follow this Override to do task
            SwingUtilities.invokeLater(new Runnable() {
                //Override will let the task run                

                @Override
                public void run() {
                    oneSecsDisplay.setIcon(new ImageIcon("images\\" + TextGrabber() + ".png"));
                    oneSecs.setText( DigitValue.getText());

                    int i = 0;

                    if (Integer.parseInt(oneSecs.getText()) == i) {
                        tenSecs.setText(Integer.toString(i++));
                    }
                }
            });
        }
    }, 0, 100, TimeUnit.MILLISECONDS); //Update will be for every 100 milliseconds concurrent to system time
} 

// Variables declaration - do not modify   
private javax.swing.JTextField oneSecs;
private javax.swing.JTextField tenSecs;
// End of variables declaration

I am sure that the error is occurring around the line int i = 0;. I am also sure that my way of increasing the value is not the best way to do this, if someone could kindly point me in the correct direction

Upvotes: 0

Views: 1244

Answers (1)

Steven Spasbo
Steven Spasbo

Reputation: 646

If I'm understanding you correctly, try tenSecs.setText(String.valueOf(Integer.parseInt(tenSecs.getText()) + 1));

Upvotes: 1

Related Questions