David Jarrin
David Jarrin

Reputation: 1749

reading ArrayList JTextFields

My program starts by prompting the user how many text fields they would like to have

public class textEvent1 implements ActionListener {    //action listener for "how many masses?"
            public void actionPerformed (ActionEvent e) {
                n = (int)(Double.parseDouble(massNumField.getText())); 

next I create a for loop to create labels and textfields (which I have created lists for because I dont know how many there will be). There are a couple of lists but I will give an example of just one.

ArrayList masses = new ArrayList();

    for(int i=1; i<=n; i++) {                                  //adds text event 2 text to the screen
                        massLabel = new JLabel("How much mass does Mass " +i+ " have? ");
                        massField = new JTextField(5);
                        masses.add(massField);

Now my problem appears to come when I try to assign an element of the masses list to a variable like so.

for(int i=1; i<=n; i++) {
                        mass =  Double.parseDouble(((JTextComponent) masses.get(i)).getText());

I have tried a couple of things...mass = masses.get(i).....mass = masses.get(i).getText()) and so on and so on. I either keep getting errors such as Null pointer exceptions or things saying I cant parseDouble an Object.

There errors that arrise for this example are as below

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 3
    at java.util.Vector.elementAt(Unknown Source)
    at acmx.export.java.util.ArrayList.get(ArrayList.java:54)
    at Orbit$textEvent2.actionPerformed(Orbit.java:151)

line 151 is

mass =  Double.parseDouble(((JTextComponent) masses.get(i)).getText());

Upvotes: 0

Views: 437

Answers (1)

kiheru
kiheru

Reputation: 6618

When creating the JTextFields, you do:

for(int i=1; i<=n; i++) {
    ...

Note that List indices start at 0, so when you retrieve the items with a similar loop, using i as the index, you are trying to access one past the last item. Change the reading loop indices to:

for (int i = 0; i < n; i++) {
    ...

Or you could use an enhance for loop, unless you need to use an ancient java version:

for (Object massField : masses) {
    mass =  Double.parseDouble(((JTextComponent) massField).getText());
    ...

(Then you should really use generics too, if the java version supports them).

Upvotes: 2

Related Questions