我无法将组合框的值传递到对象中。

我的项目中有一堆枚举,我用它们来表示组合框中的值,但是当我将这些值传递到我的“pizza”类中时,它给了我错误。


public class Pizza {

    private Size size;

    private Crust crust;

    private Sauce sauce;

    private Topping topping1;

    private Topping topping2;

    public Pizza(Size size,Crust crust, Sauce sauce,

                 Topping topping1,Topping topping2){

        this.size=size;

        this.crust=crust;

        this.sauce=sauce;

        this.topping1=topping1;

        this.topping2=topping2;

    }

    //blah blah

------------------------------------------

//This is one of my enums.

public enum Size {

    SMALL(9.45),MEDIUM(11.87),LARGE(15.9);

    private double size;

Size(double size){this.size=size;}

public double getSize(){return this.size;}

public String getSizeAsString(){return String.valueOf(size);}


}

-------------------------------------------

public class PizzaForm extends javax.swing.JFrame {


    public PizzaForm() {

        initComponents();

        initiateComboBoxes();


    }

public void initiateComboBoxes(){

    cboSize.setModel(new DefaultComboBoxModel<>(Size.values()));

}

---------------------------------------------

private void btnAddToOrderActionPerformed(java.awt.event.ActionEvent evt) {                                              

        //when button clicked..

        Pizza pizza=new Pizza(cboSize.getSelectedItem(),cboCrust.getSelectedItem(),cboSauce.getSelectedItem(),cboTopping1.getSelectedItem(),cboTopping2.getSelectedItem());

    }

错误位于倒数第二行。它突出显示了我的整个错误行。谁能告诉我可能是什么问题?我没有将任何东西转换为“大小”,所以我不知道问题是什么。谢谢


POPMUISE
浏览 86回答 1
1回答

眼眸繁星

JComboBox#getSelectedItem()不是“泛型化”,因此只知道返回原始对象类型。您需要将从此方法返回的对象强制转换为适当的类型,例如在本例中为 Size。所以:Pizza&nbsp;pizza&nbsp;=&nbsp;new&nbsp;Pizza((Size)&nbsp;cboSize.getSelectedItem(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Crust)&nbsp;cboCrust.getSelectedItem(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Sauce)&nbsp;cboSauce.getSelectedItem(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Topping)&nbsp;cboTopping1.getSelectedItem(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(Topping)&nbsp;cboTopping2.getSelectedItem());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java