Search code examples
javaarraysswinglayoutjtextfield

Array of JTextFields in a for loop that adds itself to the layout


I have a problem with adding this JTextFields on the layout. The only JTextField that would appear is just 1 instead of 18 or so. My plan is to have 20 JTextFields on my layout. With this 20 textfields, they will have random x + y values, and also random position on the layout. These are my codes:

import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class JtextArray extends JFrame
{    
    JTextField[] allField = new JTextField [20];

    Random rand = new Random();
    int x = rand.nextInt(100);int y = rand.nextInt(100);
    int xpost = rand.nextInt(300); int ypost = rand.nextInt(150);

    JtextArray(){ 
    super("dsd");
    setLayout(null);
    for(int x = 0;x<=18;x++){
        System.out.println(x);
        allField[x] = new JTextField(String.format("        %s + %s", x , y));
        allField[x].setBounds(xpost, ypost, 100, 30);
        add(allField[x]);
    }
    }}

my Main Class

import javax.swing.JFrame;

public class ArraySample extends JFrame{
    public static void main(String[] args){
        JtextArray object = new JtextArray();
        object.setDefaultCloseOperation(EXIT_ON_CLOSE);
        object.setSize(400,400);
        object.setVisible(true);

    }
}

Solution

  • Your textFields have same co-ordinates!

    use rand.nextInt inside your for loop.