http://i.stack.imgur.com/68ou3.png I have a class named trader
and I have another class named product
.
My task is:
the trader should buy many products (an object array of class
product
)
Now I want the user to enter the name of the product
in a JTextField
(using something like Product k=new Product();
)
I want the JTextField to find the corresponding object from the product
objects (somehow using/implementing the equals(k)
method) and stored in the array of objects he has bought ( product
) in the trader
every time he adds a product this way.
How can this be implemented?
You can't expect the user to enter the variable name of an object to the JTextField and add that object accordingly. Even if you can do it by reflection, it is not to be used in that manner.
You can perhaps create a Product
class with a name
attribute within the Product
class:
class Product
{
private String name;
//Your other attributes here..
public Product(String name){
this.name = name;
}
}
As the user enters the name of the product into the textfield and click the button, you can add the product according to its name as such:
@Override
actionPerformed(ActionEvent e){
traderList.add(new Product(txtProduct.getText()));
}
The traderList can be an arrayList which stores various products. You may also add some checks on the product name before adding them to the list.
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.