![](/img/trans.png)
[英]Java - Read Text File, Store Contents in ArrayList, Print ArrayList
[英]Store Jtextfield input in Arraylist then print contents of Arraylist
這是我第一次創建 GUI。 我可以很好地創建文本字段,但在收集用戶輸入並將其輸入存儲到 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);
如果用戶在 textField2 中輸入“4”,我希望“輸入帳戶編號”和“輸入帳戶數據”出現四次(產生 8 個新文本字段)
我希望用戶能夠單擊“存儲”按鈕,將文本字段 1-5(如果他們想輸入大量帳戶,則更多)放入一個數組列表中,該列表可以在以后檢索並打印所有存儲的數組信息(顯示所有居民和所有帳戶信息),類似於以下內容:
ArrayList accounts = new ArrayList<>();
\n\n賬戶示例Account = new Account(); exampleAccount.setFirstName("John"); exampleAccount.setLastName("Doe"); exampleAccount.setBalance(101.13d);
\n\n帳戶。添加(示例帳戶);
\n\nfor(Account account : accounts) { System.out.println("Name: " + account.getFirstName() + " " + account.getLastName() + ". Balance: " + account.getBalance()); // 或者覆蓋 Account 的 toString() 方法並執行 System.out.println(account.toString()) }
想要“重置”表單,以便用戶每次單擊“商店”后,他們都可以輸入新居民的信息。
我該怎么做?
你需要這樣的東西..
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);
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.