gpt4 book ai didi

java - GUI 将 JTextField 添加到 ArrayList

转载 作者:行者123 更新时间:2023-11-30 06:12:36 24 4
gpt4 key购买 nike

我删除了我的其他帖子,因为有人告诉我它不具体,然后回来提出更具体的问题,这里是......

该程序应该接收联系信息(名字和姓氏、电话、电子邮件),然后您单击添加按钮,将创建一个联系人对象并转到 ArrayList。然后,当单击查看按钮时,您将看到添加到其中的所有联系人。

我一直在观看有关如何使用 GUI 的教程和阅读书籍,并且能够创建一个包含所有必要内容的窗口来添加联系信息。

我的问题:我遇到的问题是如何将此信息添加到数组列表

在弄清楚如何添加信息后,我将研究如何在单击查看按钮时查看它。

任何帮助我前进的帮助或提示都将不胜感激!

public class InputForm extends JFrame {
private static JPanel panel;
private static JLabel firstNameLabel;
private static JLabel lastNameLabel;
private static JLabel phoneNumLabel;
private static JLabel emailLabel;
private static JLabel contactMessage;
private static JTextField firstNameInput;
private static JTextField lastNameInput;
private static JTextField phoneInput;
private static JTextField emailInput;
private static JButton addButton;
private static JButton viewButton;
private String fn;
private String ln;
private String ph;
private String em;
private List<String> list = new ArrayList<String>();

public InputForm() {
int windowWidth = 650;
int windowHeight = 550;

//Window title
setTitle("CONTACT FORM");
//Set window size.
setSize(windowWidth, windowHeight);
//Exit on close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Buld the panel and add it the the JFrame.
buildPanel();
//Add the panel to the frames content pane
add(panel);
//Display the window.
setVisible(true);
}

private void buildPanel() {

panel = new JPanel();

addButton = new JButton("Add Contact");
viewButton = new JButton("View Contacts");

firstNameLabel = new JLabel("First Name");
firstNameInput = new JTextField(10);
lastNameLabel = new JLabel("Last Name: ");
lastNameInput = new JTextField(10);
phoneNumLabel = new JLabel("Phone Number: ");
phoneInput = new JTextField(10);
emailLabel = new JLabel("Email: ");
emailInput = new JTextField(10);


/*Add labels, text fields and buttons to the panel*/
panel.add(firstNameLabel);
panel.add(firstNameInput);
panel.add(lastNameLabel);
panel.add(lastNameInput);
panel.add(phoneNumLabel);
panel.add(phoneInput);
panel.add(emailLabel);
panel.add(emailInput);
panel.add(addButton);
panel.add(viewButton);

theHandler handler = new theHandler();
addButton.addActionListener(handler);
viewButton.addActionListener(handler);

}


private class theHandler implements ActionListener {

public void actionPerformed(ActionEvent event) {
fn = firstNameInput.getText();
ln = lastNameInput.getText();
ph = phoneInput.getText();
em = emailInput.getText();
Contact con = new Contact(fn, ln, ph, em);

if(event.getSource() == addButton) {
list.add(con);
}
else if(event.getSource() == viewButton) {
JOptionPane.showMessageDialog(null,"Contact Info:\n" + con);
}
else if(event.getSource() == viewButton) {
JOptionPane.showMessageDialog(null, con);
}

}

}

public static void main(String[] args) {
new InputForm();

}

}

好的,这是我根据“满载鳗鱼的气垫船”的建议创建的联系人类。

public class Contact {
private String fn;
private String ln;
private String ph;
private String em;

private List<Contact> list = new ArrayList<Contact>();

public Contact(String fn, String ln, String ph, String em) {
this.fn = fn;
this.ln = ln;
this.ph = ph;
this.em = em;
}
public String getFirstName() {
return fn;
}
public void setFirstName(String fn) {
this.fn = fn;
}

public String getLastName() {
return ln;
}
public void setLastName(String ln) {
this.ln = ln;
}

public String getPhone() {
return ph;
}
public void setPhone(String ph) {
this.ph = ph;
}

public String getEmail() {
return fn;
}
public void setEmail(String em) {
this.em = em;
}

public String toString() {
return "First Name: " + getFirstName() + "\n" +
"Last Name: " + getLastName() + "\n" +
"Phone Number: " + getPhone() + "\n" +
"Email: " + getEmail() + "\n";
}

public static void main(String[] args) {
new InputForm();

}
}

最佳答案

建议:

  1. 首先,也是最重要的,创建一个非 GUI Contact 类,一个包含名字、姓氏、电话号码和电子邮件地址的字段,一个带有将四个字段的字符串作为参数的合适的构造函数,一个带有getter 和 setter 方法。
  2. 也给联系一个体面的public String toString()覆盖方法。当您要调试代码时,这会非常很有帮助。
  3. 将您的列表设为 List<Contact>和 ArrayList 一样——它应该是一个 ArrayList<Contact> .
  4. 在您的处理程序 ActionListener 中,从 JTextFields 中提取字符串,并创建一个 Contact 对象。
  5. 然后将联系人对象添加到您的列表中。
  6. 在向列表中添加数据时,无需像您正在做的那样使用迭代器。您只需创建一个 Contact 实例并调用 List 的 add(...)方法,仅此而已。
  7. 大功告成。

附带建议(与您的主要问题无关):

  1. 阅读并使用布局管理器,因为使用它们可以使您的 GUI 看起来更令人愉悦并且功能更强大。
  2. 对于这种类型的数据输入,我喜欢使用 GridBagLayout,而且我通常会为我的类提供一个用于创建 GridBagConstraint 的辅助方法以简化其使用。
  3. 我尽量避免扩展 JFrame,因为这会迫使您创建和显示 JFrame,而这通常需要更大的灵 active 。事实上,我敢打赌,我创建的和看到的大多数 Swing GUI 代码都扩展 JFrame,而且实际上您很少想这样做这。更常见的是,您的 GUI 类将用于创建 JPanel,然后可以将其放入 JFrames 或 JDialogs,或 JTabbedPanes,或通过 CardLayouts 在任何需要的地方进行交换。这将大大增加您的 GUI 编码的灵 active 。
  4. 体面的 toString 方法会显示类字段的状态。例如,对于联系人类,它将创建并返回一个字符串,其中包含该联系人的名字、姓氏、电话号码和电子邮件地址。然后,如果您需要调试您的程序并遍历 List 以查看它包含什么,您可以简单地调用 System.out.println(myContact);在列表中的每个联系人项目上,将打印有用的信息。此外,如果您在 JList 中显示 List,默认情况下会使用 toString 来显示 JList 模型中的每个项目。
  5. 您的代码严重过度使用了 static 修饰符,这使得它不是面向对象的,因此代码有些不灵活。我建议您的大部分字段都应该是非静态实例字段。

例如,像这样的东西:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class InputForm2 extends JPanel {
private static final int COLS = 10;
private List<ShoppingItem> shoppingList = new ArrayList<>();
private JTextField nameField = new JTextField(COLS);
private JTextField skuField = new JTextField(COLS);
private JTextField priceField = new JTextField(COLS);

public InputForm2() {
JPanel formPanel = new JPanel(new GridBagLayout());
formPanel.add(new JLabel("Item Name:"), createGbc(0, 0));
formPanel.add(nameField, createGbc(1, 0));
formPanel.add(new JLabel("Item SKU:"), createGbc(0, 1));
formPanel.add(skuField, createGbc(1, 1));
formPanel.add(new JLabel("Price:"), createGbc(0, 2));
formPanel.add(priceField, createGbc(1, 2));

JPanel btnPanel = new JPanel(new GridLayout(1, 0, 4, 4));
btnPanel.add(new JButton(new AddItemAction("Add Item")));
btnPanel.add(new JButton(new DisplayItemsAction("Display Items")));

setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(formPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}

private static GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
int inset = 4;
int leftInset = x == 0 ? inset : 3 * inset;
gbc.insets = new Insets(inset, leftInset, inset, inset);
return gbc;
}

private class AddItemAction extends AbstractAction {
public AddItemAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0); // mnemonic keystroke
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO finish this
// get Strings from fields
// create ShoppingItem object
// add to shoppingList

}
}

private class DisplayItemsAction extends AbstractAction {
public DisplayItemsAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0); // mnemonic keystroke
putValue(MNEMONIC_KEY, mnemonic);
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO finish this

}
}

private static void createAndShowGui() {
InputForm2 mainPanel = new InputForm2();

JFrame frame = new JFrame("InputForm2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

class ShoppingItem {
private String name;
private String skuNumber;
private double price;
public ShoppingItem(String name, String skuNumber, double price) {
this.name = name;
this.skuNumber = skuNumber;
this.price = price;
}
public String getName() {
return name;
}
public String getSkuNumber() {
return skuNumber;
}
public double getPrice() {
return price;
}

@Override
public String toString() {
return String.format("name: %s, sku: %s, price: $%0.df", name, skuNumber, price);
}
}

请注意,这使用了不同的非 GUI 类和 JTextFields,但我希望您获得并借鉴想法,而不是代码。 :)


编辑

关于您更新的问题,您的错误消息告诉您确切出了什么问题。这段代码:

    if(event.getSource() == addButton) {
fn = firstNameInput.getText();
ln = lastNameInput.getText();
ph = phoneInput.getText();
em = emailInput.getText();
list.add(fn + "\n" + ln + "\n" + ph + "\n" + em + "\n");

不会将联系人对象添加到列表中,而是尝试将连接的字符串(一个以换行符作为分隔符???)添加到列表中,但此处不允许也不需要字符串。同样按照我上面的建议,您应该使用文本字段中保存的字符串,创建一个联系人对象,然后将该对象添加到您的列表中。

关于java - GUI 将 JTextField 添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674293/

24 4 0