Odjegba Jonathan
Odjegba Jonathan

Reputation: 13

How do I get the values of a dynamically created textfield

Please can anyone help me out with this code of mine. I am working on a project that requires a dynamically created text field, although I was able to create the text field but I could not get the user input which I need to store in an array. Here is the code I used;

Public void actionPerformed(ActionEvent e){
   String value = textField.getText();
   int values = Integer.parseInt(value);
   int sum = 10;
   for(int I=0; I < values; I++){
       TextField field = new TextField();
       field.setBound(10,sum,107,22);
       Panel.add(field);
       sum += 28;
       }
   }
});

But I could not write any successful code to get the values of the textFields.

Upvotes: 0

Views: 78

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your problem is one of access to reference -- meaning, once you create the object, you have no easy way to get a decent reference to it when you need it. A solution is to use a collection such as an ArrayList<TextField> as a field of your class, and then place your created objects into this collection. Then later if you need them, you can get them from the collection easily.

A bit of side recommendations:

  • Why AWT components and not Swing? In other words, use an ArrayList<JTextField> and fill it with JTextFields, not TextFields.
  • Avoid setBounds(...) and null layouts as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain.

  • Avoid "magic" numbers, such as the hard-coded numbers here: field.setBound(10,sum,107,22);

  • Use layout managers instead.
  • You will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

Upvotes: 6

Related Questions