Search code examples
javaswingarraylistjtextfield

JTextField - separation of numbers (ArrayList)


Is there any way to take several different numbers using JTextField?

For example, following numeric values are given: 2.0, 3.0, 4.0. I would like to put them into ArrayList separately.

How to handle incorrect input data ​​in order to continue the typing?

    //in this case the resulst is "arList: 1.92239991"
    textField = new JTextField("1.9, 223, 9991");
    textField.addActionListener(this);
    ArrayList<Double> arList = new ArrayList<>();

    String str = textField.getText();
    String result = str.replaceAll("\\s+","");
    String otherResult = result.replaceAll(",","");
    double d = Double.parseDouble(otherResult);
    System.out.println(d);

    arList.add(d);
    for (Double anArList : arList) {
        System.out.println("arList: " +anArList);
    }

Solution

  • If the numbers are always separated by , you can use String#split, which will return an array of values.

    String str = textField.getText();
    String[] parts = str.split(",");
    

    This will return each value between the ,, including the white space. You could then trim these results...

    for (int index = 0; index < parts.length; index++) {
        parts[index] = parts[index].trim();
    }
    

    This will now contain just the remaining text. If you must have it in a list you can use...

    List<String> values = Arrays.asList(parts);
    

    If you need it as list of Doubles, you will need to parse each element indiviudally...

    List<Double> values = new ArrayList<Double>(parts.length);
    for (String value : values) {
        values.add(Double.parseDouble(value));
    }
    

    This will still throw a parse exception if any one of the values is not a valid Double.

    A better solution might be to use a JFormattedTextField or JSpinner to collect the individual value and add each one to a list one at a time (could display them in a JList), this would allow you to validate each value as it is entered.

    Have a look at How to Use Formatted Text Fields, How to Use Spinners and How to Use Lists for more details