0

I need to add the text that is typed into a JTextField to a string array String[] by using a JButton. For example, if I type into a JTextField, I would click a JButton which would add that text into a String[]. I can't use an ArrayList for this, I must use a String stringa[].

Here's what I have so far:

      if(g.getSource() == jbutton) { 
            stringa.add(jtextfield.getText());            
}

It's very important to note I can't use an ArrayList but I don't know how to add to a String[]this way. Thank you for any help.

badcoder9
  • 1
  • 1
  • 3
    You can not add an element to an array. Arrays have constant length in Java. you need to create a new array with `length + 1` from the old one and assign the last value. – Samuel Philipp Apr 23 '19 at 21:32
  • Look here: [How to add new elements to an array?](https://stackoverflow.com/q/2843366/9662601) (possible duplicate) – Samuel Philipp Apr 23 '19 at 21:33

1 Answers1

0

What about doing something like this?

List<String> elems = new ArrayList<>();

elems.add(input.getText());

String[] out = new String[elems.size()];

out = elems.toArray(out);

This way you can add items to a list and then handle it as an array

Source: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-T:A-

admlz635
  • 1,001
  • 1
  • 9
  • 18