Reputation: 59
I have created buttons inside a panel using Java Swing. I have a button "Produce" that when clicked, I need it to create an object from type Produce (which is defined in another class and has items such as vendor, weight, and price).
When the button is clicked, the Produce object should be created using information that a user has typed in to the text fields in the same panel. So if a user typed in the vendor, weight, and price for an item into the textfields, the Produce object needs to be created with those values.
So far I have:
public void createButtons() {
JButton produceBtn = new JButton("Produce");
JButton prepMealBtn = new JButton("Prepared Meal");
infoPanel.add(produceBtn, BorderLayout.SOUTH);
infoPanel.add(prepMealBtn, BorderLayout.SOUTH);
produceBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if(source == produceBtn){
Produce myProduce = new Produce();
}
}
}
}
But I can't figure out how to do the mentioned part above.
Upvotes: 2
Views: 1583
Reputation: 56413
the Produce object should be created using information that a user has typed in to the text fields in the same panel. So if a user typed in the vendor, weight, and price for an item into the textfields, the Produce object needs to be created with those values.
First, you'll need to create some sort of list/array to hold the created objects.
List<Produce> produce = new ArrayList<>(); // make this global within the class
then, you have two options, either overload the Produce
constructor and create another constructor to take 3 params (vendor
, weight
, and price
):
Example constructor:
public Produce(type param1, type param2, type param3){ //Constructor to take 3 params
// assign the values appropriately
}
or create setter methods:
public void setVender(type vender){
// assign the values appropriately
}
public void setWeight(type weigth){
// assign the values appropriately
}
public void setPrice(type price){
// assign the values appropriately
}
then you can do this:
if(source == produceBtn){
String vender = someTextField.getText();
String weight = someTextField.getText();
String price = someTextField.getText();
//perform any conversion from string to numbers if needed.
/*
*/
//then create the object
Produce myProduce = new Produce(vender,weight,price);
// make sure the order in which you input the data into the arguments of the constructor above is the same as the order in which the constructor definition of the Produce class is.
produce.add(myProduce);
}
or you can use the setter methods.
Lastly but not least, you seem to have a typo with addActionListener
, you're missing the closing )
.
Also, you can simplify your code by using lambda expression:
produceBtn.addActionListener(e -> {
Object source = e.getSource();
if(source == produceBtn){
// do something
}
});
Upvotes: 2