Results 1 to 5 of 5
Thread: Putting controls in arrays?
- 01-31-2008, 06:27 PM #1
Member
- Join Date
- Jan 2008
- Posts
- 7
- Rep Power
- 0
[Resolved] Putting controls in arrays?
Hello all, I couldn't find anything under "control array(s)", so I hope you can answer this for me.
Is it possible to put controls in arrays (ie,
), and then modify them (myArray[1].setText)? If so, what sort of data type would the array be?Java Code:public static [i]someSortOfDataType[/i][] myArray = {jLabel1,jLabel2,etc};
I am aware of a fairly long winded bit of code that creates the controls at runtime (which would be a little annoying to use), but I was wondering if there was another way.
Thanks in advance.Last edited by Cymro; 02-02-2008 at 09:21 AM. Reason: Found an answer
- 01-31-2008, 10:56 PM #2
the easiest way is to declare Object[] array if you have different kinds of controls (if all are JLabel there is no problem ,simply declase JLabel[] ), and each time you need to use a method, you first check if current element is of the class you wish to use like:
Java Code:if(myArray[i].getClass().equals(JLabel.getClass()) ) //do what you want
- 01-31-2008, 11:28 PM #3
Member
- Join Date
- Jan 2008
- Posts
- 7
- Rep Power
- 0
Thanks. Before I start doing a test program (tomorrow, as it happens), is there a way of using JLabel[] for existing jLabels, or must they be added at runtime?
- 01-31-2008, 11:37 PM #4
Indeed if you do not know the precise number of JLabels, you can use the java.util.ArrrayList class, which allow you to add an object at runtime, each time you want:
Usign this object (google it and you'll find how to use it) you have no problem of what you add runtime or not.Java Code:ArrayList<JLabel> array = new ArrayList<JLabel>(); . . . array.add(jLabel1); array.add(jLabel2); array.add(jLabel3);
- 02-01-2008, 06:54 PM #5
Member
- Join Date
- Jan 2008
- Posts
- 7
- Rep Power
- 0
Thanks very much again, and it seems that I can do that.
However, if I try something like this, attatched to a button:
It gives me an error of "Array required, but java.util.ArrayList<javax.swing.JLabel> found". I can't quite comprehend what it's trying to tell me :confused:Java Code:for (int i = 0 ; i < 3 ; i++){ labRay[i].setText("This label is in the array"); }
EDIT: Aha! Got it. I had to use labRay.get(i).setText instead. Thanks again for your help.Last edited by Cymro; 02-02-2008 at 09:20 AM. Reason: found an answer
Similar Threads
-
Putting code together.
By newbee in forum New To JavaReplies: 3Last Post: 04-17-2008, 03:53 AM -
Putting your own type in a Set
By Java Tip in forum java.langReplies: 0Last Post: 04-15-2008, 07:32 PM -
new to arrays
By jimJohnson in forum New To JavaReplies: 1Last Post: 04-08-2008, 02:45 PM -
2D-Arrays
By kbyrne in forum New To JavaReplies: 1Last Post: 02-07-2008, 10:08 PM -
Tree controls using Swing
By kabir in forum AWT / SwingReplies: 1Last Post: 01-05-2008, 09:48 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks