Search code examples
javauser-interfacejbuttonjtextfield

Java GUI Creating Components


I hope it is correct term-wise to say that components in a GUI is like JButton, JPanel, JTextField, all that good stuff.

I want to create a text field that takes in an integer. Then a submit button can be pressed and based on the integer that was inputted, create that many textfields in a popup window or whatever.

I have no clue, could someone get me started in the right direction?

The trouble I'm having is that I have no clue how to create a for loop to create the GUI components. I mean if I have a for loop and do something like:

print("JTextField num1 = new JTextField()");

then in a for loop it will only create 1 text field when I want many. How do I generically create variables of JTextFields?

Thanks for your help...


Solution

  • Use an appropriate LayoutManager (e.g. GridLayout) to create and add your textfields.

    for (i = 0; i < numberOfTextFields; i++) {
        JTextField textField = new JTextField();
        container.add(textField);
        /* also store textField somewhere else. */
    }