1

I've written a GUI for a simulation project that I'm doing, and in the event handling code of the window, I have, for instance,

private void timestepKeyTyped(java.awt.event.KeyEvent evt) {
    String text = timestep.getText();
    AMEC.steptime = Integer.parseInt(text);
}

where I would like to assign any input typed into field timestep to be assigned to AMEC.steptime. I do this for all textfields.

However, my simulation doesn't run properly when passed these parameters, and upon debugging I found that only the first character gets parsed to int. For instance, if I type "31", then the value assigned to AMEC.steptime becomes 3 instead of 31.

How do I fix this?

Martin
  • 277
  • 2
  • 5
  • 17

1 Answers1

4

The problem you are facing is that you are using a KeyListener. Just don't use it, use an ActionListener and when you hit ENTER actionPerformed is executed. Then you can put the same code an will run like a charm.

Use swing not awt.

Example how to use it:

import first:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;

Then in somewhere in your code

JTextField textfield = new JTextField();
        textfield.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField timestep =(JTextField) e.getSource();// you could use this or just your variable.
                String text = timestep.getText();
                AMEC.steptime = Integer.parseInt(text);
            }

        });

As a side note, you would be interested in only allowing in this textfield number values. Read more in how to make it in this previous question. Restricting JTextField input to Integers

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53