java - How can I create a JTextField array? -
i want add together many text fields project , decided utilize arrays because 22 text fields have same attributes.
i had tried jtextfield txtfld[] = new jtextfield[5];
. has no parameter errors when seek run program, shows in console
exception in thread "main" java.lang.nullpointerexception
i don't want utilize
jtextfield txtfld[] = new jtextfield[]{ new jtextfield(10), ... ... ... // repeat same code 20 times };
because takes many lines , text fields of same type anyway. want array of text fields same length , utilize mainpanel(txtfld[0]); ... mainpanel(txtfld[21]);
is possible create text field array in single line of code?
as i'm new so, reply question it's repeated question. i'm writing answer:
it's unclear fields jtextfield aray or constant. if component array itself, consider using .length array field when iterating. reduces code maintenance:
container c = getcontentpane(); jtextfield[] fields = new jtextfield[22]; (int = 0; < 22; i++) { fields[i] = new jtextfield("your value"); //you can add together listener jtextfield here c.add(fields[i]); }
note uppercase variables used constants under java naming conventions.
the answer's been copied here. couldn't mark question duplicate.
java arrays swing nullpointerexception jtextfield
No comments:
Post a Comment