简体   繁体   English

在按钮单击/ actionEvent 上创建类的新对象

[英]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().决定简单地在 actionListener 之外创建一个名为chairPrice 的方法会更容易,该方法可以通过名为 getItemPrice() 的方法递增。 This has been used to calculate the total price of items and works 100%这已被用于计算物品和作品的总价 100%

You need to use the Object.equals() method.您需要使用Object.equals()方法。

@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编辑以回应 OP 的评论

I'm not exactly sure what you're wanting.我不确定你想要什么。 myChair isn't the name of your chair. myChair不是你椅子的名字。 It's the name of the variable.这是变量的名称。 It has no effect on Chair at all.它对Chair完全没有影响。 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 .如果您想创建一个新的Chair对象并使整个班级都可以使用它,您将需要添加一个新的字段变量或创建一个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());
     }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM