Home > Enterprise >  Create a method to create more textfields based on user input in Java
Create a method to create more textfields based on user input in Java

Time:11-13

I need to create a method that takes an integer and creates textfields according to the integer.

For example:

createJextField(5) => ["5 textfields are created"]

The thing is, I can't return the textfields since the variable that holds the textfields is used inside a for loop. Here is what I have so far:

static JTextField createSlot(int number) {
    for (int i = 0; i < number; i  ) {
        JTextField slot = new JTextField();
    }
    return slot;
}

CodePudding user response:

Your code is simply redefining a value a bunch of times and returning a single JTextField. You need something more like (and I'm not testing this code so typos are likely):

public void addTextFields(int numToAdd, Container container) {
    for (int i = 0; i < numToadd; i  ) {
        container.add(new JTextField());
    }
} 

CodePudding user response:

You need to return an array or a collection (list) of text fields:

  • Array
static JTextField[] createSlot(int number) {
    JTextField[] slot = new int[number];

    for (int i = 0; i < number; i  ) {
        slot[i] = new JTextField();
    }
    return slot;
}

Using Stream::generate:

static JTextField[] createSlot(int number) {
    return Stream.generate(JTextField::new)
                 .limit(number)
                 .toArray(JTextField[]::new);
}

  • Create List<JTextField>
static List<JTextField> createSlot(int number) {
    List<JTextField> list = new ArrayList<>(number);

    for (int i = 0; i < number; i  ) {
        list.add(new JTextField());
    }
    return list;
}

Using Stream API

static List<JTextField> createSlot(int number) {
    return Stream.generate(JTextField::new)
                 .limit(number)
                 .collect(Collectors.toList());
}
  • Related