我的项目中有一堆枚举,我用它们来表示组合框中的值,但是当我将这些值传递到我的“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()); }错误位于倒数第二行。它突出显示了我的整个错误行。谁能告诉我可能是什么问题?我没有将任何东西转换为“大小”,所以我不知道问题是什么。谢谢
1 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
JComboBox#getSelectedItem()
不是“泛型化”,因此只知道返回原始对象类型。您需要将从此方法返回的对象强制转换为适当的类型,例如在本例中为 Size。
所以:
Pizza pizza = new Pizza((Size) cboSize.getSelectedItem(), (Crust) cboCrust.getSelectedItem(), (Sauce) cboSauce.getSelectedItem(), (Topping) cboTopping1.getSelectedItem(), (Topping) cboTopping2.getSelectedItem());
添加回答
举报
0/150
提交
取消