How to Read an Integer With the JTextField

How to Read an Integer With the JTextField thumbnail
A JTextField string can be interpreted as an integer, if properly formatted.

The Java language can be used to develop rich, interactive applications on both the Web and native applications. The JTextField class handles string input from a form embedded within a Java application. Your user may enter an integer in the text field that needs to be converted from a string before programmatic use.

Instructions

    • 1

      Create a new JTextField within your display class, such as JFrame or JPanel, that implements ActionListener. The integer 10 creates a text field with 10 columns.

      public class myDemo extends JPanel implements ActionListener {
      protected JTextField myJTextField;
      protected int myInteger;
      ...
      public doDemo() {
      my_JTextField = new JTextField(10);
      ...
      }
      ...
      }

    • 2

      Add an action listener to my_JTextField to handle the response when text is entered.

      my_JTextField.addActionListener(this);

    • 3

      Add a method to your myDemo class to handle the response when text is entered.

      public void actionPerformed (ActionEvent my_event) {
      ...
      }

    • 4

      Use the Integer.parseInt() function to parse the string from your JTextField into an int. The function will return an error if your JTextField does not contain an integer, so embed it in a try statement.

      try{
      int myInteger = Integer.parseInt( my_JTextField.getText() );
      } except (Exception ecp) { System.out.println(ecp); }

Related Searches:

References

  • Photo Credit Comstock/Comstock/Getty Images

Comments

Related Ads

Featured