当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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.

网友答案:

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);
网友答案:

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;
}
网友答案:

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};
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: