Creating new object of a class on button click / actionEvent

亡梦爱人 提交于 2019-12-11 18:19:20

问题


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%


回答1:


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());
     }
  }
}


来源:https://stackoverflow.com/questions/10373747/creating-new-object-of-a-class-on-button-click-actionevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!