/image/68ou3.png我有一个名为 trader
的类,还有另一个名为 product
的类。
我的任务是:
the trader should buy many products (an object array of class
product
)
现在我希望用户在 JTextField
中输入 product
的名称(使用类似 Product k=new Product();
)
我希望 JTextField 从 product
对象中找到相应的对象(以某种方式使用/实现 equals(k)
方法),并将其存储在他每次以这种方式添加产品时在 trader
中购买的对象数组 (product
) 中。
如何实现?
最佳答案
您不能期望用户将对象的变量名称输入到 JTextField 并相应地添加该对象。即使您可以通过反射来做到这一点,也不能以这种方式使用它。
您也许可以在 Product
类中创建一个带有 name
属性的 Product
类:
class Product
{
private String name;
//Your other attributes here..
public Product(String name){
this.name = name;
}
}
当用户在文本字段中输入产品名称并单击按钮时,您可以根据产品名称添加产品,如下所示:
@Override
actionPerformed(ActionEvent e){
traderList.add(new Product(txtProduct.getText()));
}
traderList 可以是一个存储各种产品的 arrayList。您还可以在将产品添加到列表之前对产品名称进行一些检查。
关于java - 我如何使用 Jtextfield 命名对象数组中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165842/