简体   繁体   中英

Store Jtextfield input in Arraylist then print contents of Arraylist

This is my first time creating a GUI. I can create text fields just fine, but am having trouble collecting user input and storing their input into an Arraylist.

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.JTextField;

textField1 = new JTextField("Enter resident name",20); 
  add(textField1); 

  textField2 = new JTextField("How many accounts to enter data for?",20);
  add(textField2); 

  textField3 = new JTextField("Enter account #",20);
  add(textField4); 

  textField3 = new JTextField("Enter data for account",20);
  add(textField5); 
  1. If the user enters "4" into textField2, I would like "Enter account #" and "Enter data for account" to then appear four times (resulting in 8 new textfields)

  2. I would like the user to be able to click a "Store" button that places textfields 1-5 (and more if they want to enter a lot of accounts) into an arraylist that can later be retrieved and print all stored array info (show all resident and all accounts info), similar to something like below:

     ArrayList accounts = new ArrayList<>();

    \n\n

    Account exampleAccount = new Account(); exampleAccount.setFirstName("John"); exampleAccount.setLastName("Doe"); exampleAccount.setBalance(101.13d);

    \n\n

    accounts.add(exampleAccount);

    \n\n

    for(Account account : accounts) { System.out.println("Name: " + account.getFirstName() + " " + account.getLastName() + ". Balance: " + account.getBalance()); // Or override Account's toString() method and do System.out.println(account.toString()) }

  3. Would like the form "reset" so that after each time the user clicks "Store" they can enter a new resident's information.

How do I go about doing this?

You need something like this..

    textField1 = new JTextField("Enter resident name", 20);
    add(textField1);

    textField2 = new JTextField("How many accounts to enter data for?", 20);
    add(textField2);

    textField2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            int count = Integer.valueOf(textField2.getText());

            for (int i = 1; i <= count; i++) {
                textField3 = new JTextField("Enter account #", 20);
                add(textField4);

                textField3 = new JTextField("Enter data for account", 20);
                add(textField5);
            }

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM