Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays" Watch "Arrays" New topic


Matthew Jones
Ranch Hand

Joined: Dec 21, 2000
Posts: 68
I'm trying to create an array of Labels
I declare the array using:
Label example[];
at the top of me class, and in the constuctor tries to initialize it with:
Label[] example = { "ex1", "ex2", "ex3", "ex4", "ex5", "ex6 };
When I try to compile it, I get errors:
Incompatible type for array. Can't convert java.lang.String to java.awt.Label
Is there any way to initialize the whole array at once, or do I need to do something like:
example[0] = new Label("ex1");
example[1] = new Label("ex2");

Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
Try this...
String example[];
In your constructor...
example = { "ex1", "ex2", "ex3", "ex4", "ex5", "ex6 };

So much trouble in the world -- Bob Marley
Matthew Jones
Ranch Hand

Joined: Dec 21, 2000
Posts: 68
While that would probably work, I'm trying to create an array of Labels that I want to user further in my program, not Strings. I can probably just initialize them seperatly, but as I have a LOT of arrays that I am going to end up needing, I wanted to know if there was a quicker, more efficient way of doing this.
Pat Barrett
Ranch Hand

Joined: Jan 03, 2001
Posts: 63
I just heard (very briefly) about vectors being used for arrays of objects. Would a vector work?
sebu koleth

Joined: Nov 26, 2000
Posts: 4
As far as I can see what you have been trying to do is assign an array containing Strings to an array containing Labels. But this is not possible. You will have to first create Label objects with the Strings and then initialise the array. Or create the array of Label objects with empty constructors and then set the text of each label. If someone else can suggest a better solution please do so.
Matthew Jones
Ranch Hand

Joined: Dec 21, 2000
Posts: 68
I don't know much about vectors at this point, so I think I will stick with the arrays.
Thanks for the info, I was just hoping there was a quicker way, but I guess I'll have to create all the Labels individually.
Thanks, guys
Peter Tran

Joined: Jan 02, 2001
Posts: 783
Try this:

Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

The easiest way to probably do this is to have an array of Labels and an array of Strings:
Label example[];
String words[] = { "ex1", "ex2", "ex3", "ex4", "ex5", "ex6" };
example = new Label[words.length];
for ( int i = 0; i < words.length; i++ )
example[i] = new Label( words[i] );

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
I agree. Here's the link:
subject: Arrays
It's not a secret anymore!