Search code examples
javaarraysswingjtextfieldparseint

JTextField to int[] array?


I'm working on my graphic user interface for a application I'm creating. Basically there is this JTextField that the user has to input integers. For example

25, 50, 80, 90

Now, I have this other class that needs to get those values and put them in an int Array.

I've tried the following.

guiV = dropTheseText.getText().split(",");

And in the other class file I retieve the String, but I have no idea how to get the value for each one.

In the end I'm just trying to get something like

int[] vD = {textfieldvaluessplitbycommahere};

Still fairly new to Java but this has me crazy.


Solution

  • private JTextField txtValues = new JTextField("25, 50, 80, 90"); 
    
    // Strip the whitespaces using a regex since they will throw errors
    // when converting to integers
    String values = txtValues.getText().replaceAll("\\s","");
    
    // Get the inserted values of the text field and use the comma as a separator.
    // The values will be returned as a string array
    private String[] strValues = values.split(",");
    
    // Initialize int array
    private int[] intValues = new int[strValues.length()];
    // Convert each string value to an integer value and put it into the integer array
    for(int i = 0; i < strValues.length(); i++) {
        try {
           intValues[i] = Integer.parseInt(strValues[i]);
        } catch (NumberFormatException nfe) {
           // The string does not contain a parsable integer.
        }
    
    }