Results 1 to 4 of 4
- 11-04-2011, 12:17 AM #1
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
stepping through numbered variable names
Hi,
This is probably a very easy question, I'm just going bonkers trying to guess it.
I'm writing a little program for myself to develop my skills & one thing I have in my program is a set of textfields (in swing) lets just say called Text1 to Text5.
When I hit my save button I want to set up a 'for' loop to step through 5 times & if there is text, to write the Text of the text box to an ArrayList.
for example I wrote
essentially it's the x's in brackets in lines 2 & 3 that I'm unsure of.Java Code:for (int x = 1; x<=5; x++){ if (Text(x) <"") { myArrayList.add(Text(x).getText()); } }
I dont want to statically hardcode Text1, Text2, etc, I want the code to do it for me.
I know it must be possible, I've tried no brackets, square Brackets & regular brackets all to no avail. - what do I need to do..?
Thanks in advance,
PJ
- 11-04-2011, 12:35 AM #2
Re: stepping through numbered variable names
With that syntax, the compiler will think that you are trying to call a method named Text.Text(x)
You must create all variable names when you type in the code. The compiler does not generate variable names.
You can use an array of TextFields to hold references to TestFields and then index into that array.
-
Re: stepping through numbered variable names
What you want to do is easy: you should create an array or collection of JTextFields if you desire to do something like this. (as Norm already mentioned).
The variable name is not nearly as important as you think since it almost doesn't even exist in the compiled code. What matters is the reference and an array or collection will allow you to access the references to the fields.
- 11-04-2011, 08:37 AM #4
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
Re: stepping through numbered variable names
You're exactly right.
I just thought there might be a way so that in iteration 1 it would add Text1 to the arrayList, in iteration 2 would add Text2 etc. seems that I need to dump it into an array first? (which would necessitate the same code as putting it into the ArrayList anyway!).
Oh well, it's good to try these things. Thanks for your swift responses. - Much appreciated..gif)
- PJ.
Similar Threads
-
Dynamic variable names
By reuben2011 in forum New To JavaReplies: 8Last Post: 08-31-2011, 04:42 PM -
Stepping through a text file line by line
By evanlivingston in forum New To JavaReplies: 10Last Post: 01-29-2011, 04:30 AM -
How do stop Eclipse from suggesting variable names?
By Neil_ in forum EclipseReplies: 0Last Post: 04-12-2009, 03:06 AM -
[SOLVED] Can variable names be dynamically created?
By CJSLMAN in forum New To JavaReplies: 4Last Post: 01-03-2009, 01:06 AM -
building file and variable names from variables
By madad2005 in forum New To JavaReplies: 2Last Post: 07-18-2007, 04:47 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks