繁体   English   中英

当用户单击Java Swing中的按钮时,从另一个类创建新对象

[英]Creating a new object from another class when a user clicks a button in Java Swing

我已经使用Java Swing在面板内部创建了按钮。 我有一个“ Produce”按钮,单击该按钮时,我需要它以Produce类型(在另一个类中定义,并具有诸如供应商,重量和价格之类的项目)创建对象。

单击该按钮时,应该使用用户在同一面板的文本字段中键入的信息来创建Produce对象。 因此,如果用户在文本字段中输入商品的供应商,重量和价格,则需要使用这些值来创建Produce对象。

到目前为止,我有:

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

但是我不知道如何做上面提到的部分。

应该使用用户在同一面板的文本字段中键入的信息来创建Produce对象。 因此,如果用户在文本字段中输入商品的供应商,重量和价格,则需要使用这些值来创建Produce对象。

首先,您需要创建某种列表/数组来保存创建的对象。

List<Produce> produce = new ArrayList<>(); // make this global within the class

然后,您有两个选择,要么重载Produce构造函数,然后创建另一个构造函数以接受3个参数( vendorweightprice ):

构造函数示例:

public Produce(type param1, type param2, type param3){  //Constructor to take 3 params
   // assign the values appropriately
}

或创建setter方法:

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
}

那么您可以执行以下操作:

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

或者您可以使用setter方法。

最后但并非最不重要,你似乎有一个错字addActionListener ,你就错过了截止)

另外,您可以使用lambda表达式来简化代码:

produceBtn.addActionListener(e -> {
    Object source = e.getSource();
    if(source == produceBtn){
        // do something
    }
});

暂无
暂无

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

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