user1850231
user1850231

Reputation: 21

Creating new object of a class on button click / actionEvent

Found solution

decided it was easier to simply make a method outside of the actionListener called chairPrice which can be incremented by a method called getItemPrice(). This has been used to calculate the total price of items and works 100%

Upvotes: 0

Views: 7448

Answers (1)

Tim Pote
Tim Pote

Reputation: 28029

You need to use the Object.equals() method.

@Override
public void actionPerformed(ActionEvent buttonClick)
{
   if(buttonClick.getSource().equals(guiButtons[0])) //if user clicks on 'add chair'
   {
     Chair chair = new Chair();
   }
}

Edit in response to the OP's comment

I'm not exactly sure what you're wanting. myChair isn't the name of your chair. It's the name of the variable. It has no effect on Chair at all. If you want to make a new Chair object and have it available for the whole class, you're going to need to either add a new field variable or make a list of Chair.

public class GuiClass extends JPanel implements ActionListener
{
  List<Chair> chairs = new ArrayList<Chair>(Arrays.asList(new Chair()));
  Desk myDesk = new Desk();
  Table myTable = new Table();

  @Override
  public void actionPerformed(ActionEvent buttonClick)
  {
     if(buttonClick.getSource().equals(guiButtons[0])) //if user clicks on 'add chair'
     {
       chairs.add(new Chair());
     }
  }
}

Upvotes: 1

Related Questions