Bumpy
Bumpy

Reputation: 97

finding the right code: Array of jTextField

I've been looking all over the net for a code that is something like this:

JTextField[] jt = new JTextField{jTextField1,jTextField2,..};

I had a copy of this code once and I kept it in a hard disk because I know I might use it in the future, but the disk died!

can anyone help me find this code? It gives me error so please do correct this for me. thanks!

by the way, this is an array for an existing jTextField and it runs inside a button when pressed.

EDIT: since this was flagged as possible duplicate, heres my explanation.

The classic initialization has already been tested and what ive seen yet so far in declaring jTextField array is this:

JTextField[] jt = new jTextField[10];

specifying the value then adding it.

jTextField[n] = new JTextField(jTextField1);

if i use that method, I would have to type it all over again.

jTextField[n] = new JTextField(jTextField2);
jTextField[n] = new JTextField(jTextField3);.. and so on and so forth.

now what I am looking for is what i've said on the sample code. I have used this once but I was clumsy enough not to back it up.

Upvotes: 0

Views: 175

Answers (3)

Atri
Atri

Reputation: 5831

This is wrong syntax and will throw a compilation error:

JTextField[] jt = new JTextField{jTextField1,jTextField2};

You need to do:

JTextField[] jt = new JTextField[] {jTextField1,jTextField2}; // or you can do {jTextField1,jTextField2};

I tried this and it works fine:

JTextField j1 = new JTextField();
JTextField j2 = new JTextField();
JTextField[] j = new JTextField[] {j1, j2}; 
//JTextField[] j = {j1, j2};   // This syntax also works 
System.out.println(j);

Upvotes: 1

Bumpy
Bumpy

Reputation: 97

Silly netbeans..

I closed my project down and re-opened it just to try it out. well guess what. the code works properly now.

public void arrayoftextboxes(){
     JTextField[] jt = {jTextField1, jTextField2};
}

Upvotes: 0

Pedro Martins PT
Pedro Martins PT

Reputation: 1

I think it's not possible to do what you want. Try to code some cycle to create and add JTextFields to you array.

int x = 2;
JTextField[] textFields = new JTextField[x];

for(int i = 0;i < x; i++) {
    JTextField textField = new JTextField(blabla);
    textField.setSomething();
    textFields [i] = textField;
}

Upvotes: 0

Related Questions