Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用switch case获得组合框的总和?_Java_Swing_Combobox_Sum - Fatal编程技术网

Java 如何使用switch case获得组合框的总和?

Java 如何使用switch case获得组合框的总和?,java,swing,combobox,sum,Java,Swing,Combobox,Sum,我需要得到所选ComboboxBox的总和,但如果我的switch case语句正确,则idk是正确的使用方法,idk是正确的。任何人,请帮忙。我真的很感激那些愿意帮助我的人 首先:使用“combobox.getSelectedItem()”并将那些switch语句保留在外。如果每个项目的价格不同,则使用映射;如果价格都相同,则使用if语句(combobox.getSelectedItem()如果未选择任何项目,则返回null)。使用price1.setText(newPrice)更新ui中的值

我需要得到所选ComboboxBox的总和,但如果我的switch case语句正确,则idk是正确的使用方法,idk是正确的。任何人,请帮忙。我真的很感激那些愿意帮助我的人

首先:使用“combobox.getSelectedItem()”并将那些switch语句保留在外。如果每个项目的价格不同,则使用映射;如果价格都相同,则使用if语句(
combobox.getSelectedItem()
如果未选择任何项目,则返回null)。使用
price1.setText(newPrice)
更新ui中的值。最简单的方法可能是将所有项目映射到其价格,并在itemStateChanged中使用此选项:

public class Try1 extends JFrame{

private final String [] a1 = {"","Angus Burger - P60", "Australasian Burger - P60", "BBQ Burger - P60", "Buffalo Burger - P60"};
private final String [] a2 = {"","Spaghetti - P120", "Lasagna - P120", "Carbonara - P120", "Fettuccine - P120"};
private final String [] a3 = {"","Hawaiian - P300", "Bacon & Mushroom- P300", "Cheese Overload- P300", "Vegan's Pizza- P300"};
private final String [] a4 = {"","Dry Yogurt- P100" , "Ice cream- P100", "Pie- P100", "Cheese Cake- P100"};
private final String [] a5 = {"","Soda - P50", "Juice - P50", "Fruit Punch - P50", "Smoothie - P50"};
private JComboBox x1,x2,x3,x4,x5;
private JTextField price1,price2,price3;


public Try1(){

    super("Kevin's Fast Food Delivery");
    setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JOptionPane.showMessageDialog(panel, "Please, input your order");
    panel.setLayout(new GridLayout(0,2));

    JLabel z1 = new JLabel("Burgers");
    x1 = new JComboBox(a1);
    JLabel z2 = new JLabel("Pasta");
    x2 = new JComboBox(a2);
    JLabel z3 = new JLabel("Pizza");
    x3 = new JComboBox(a3);
    JLabel z4 = new JLabel("Desserts");
    x4 = new JComboBox(a4);
    JLabel z5 = new JLabel("Drinks");
    x5 = new JComboBox(a5);

    JLabel c1 = new JLabel("Total Ordered:");
    price1 = new JTextField("0",15);
    price1.setBounds(150,150,50,20);
    price1.setEditable(false);

    JLabel c2 = new JLabel("Money on Hand:");
    price2 = new JTextField("0",15);

    JLabel c3 = new JLabel("Total:");
    price3 = new JTextField("0",15);
    price3.setBounds(150,150,50,20);
    price3.setEditable(false);


    panel.add(z1);
    panel.add(x1);
    panel.add(z2);
    panel.add(x2);
    panel.add(z3);
    panel.add(x3);
    panel.add(z4);
    panel.add(x4);
    panel.add(z5);
    panel.add(x5);



    panel.add(c1);
    panel.add(price1);
    panel.add(c2);
    panel.add(price2);
    panel.add(c3);
    panel.add(price3);
    add(panel);

    ItemListener jcb = new ItemHandler();
    x1.addItemListener(jcb);
    x2.addItemListener(jcb);
    x3.addItemListener(jcb);
    x4.addItemListener(jcb);
    x5.addItemListener(jcb);


}





private class ItemHandler implements ItemListener{


    public void itemStateChanged(ItemEvent y) {

        double value = Double.parseDouble(price1.getText());
        double r = 0;






        Object source = y.getItemSelectable();

        if(source== x1){
            int a = x1.getSelectedIndex();
                       switch(a){
                           case 0: r = 0;
                           break;

                           case 1: r = 60;
                           break;

                           case 2: r = 60;
                           break;

                           case 3: r = 60;
                           break;

                           case 4: r = 60;
                           break;
                    }
        }

            if(source== x2){
                int b = x2.getSelectedIndex();
                        switch(b){
                           case 0: r = 0;
                           break;

                           case 1: r = 120;
                           break;

                           case 2: r = 120;
                           break;

                           case 3: r = 120;
                           break;

                           case 4: r = 120;
                           break;


                   }
            }                

            if(source== x3){
                int c = x3.getSelectedIndex();
                     switch(c){
                           case 0: r = 0;
                           break;

                           case 1: r = 300;
                           break;

                           case 2: r = 300;
                           break;

                           case 3: r = 300;
                           break;

                           case 4: r = 300;
                           break;


                   }
            }

            if(source== x4){
                int d = x4.getSelectedIndex();
                   switch(d){
                           case 0: r = 0;
                           break;

                           case 1: r = 100;
                           break;

                           case 2: r = 100;
                           break;

                           case 3: r = 100;
                           break;

                           case 4: r = 100;
                           break;




                    }

            }

            if(source== x5){
                int e = x5.getSelectedIndex();

                   switch(e){
                           case 0: r = 0;
                           break;

                           case 1: r = 50;
                           break;

                           case 2: r = 50;
                           break;

                           case 3: r = 50;
                           break;

                           case 4: r = 50;
                           break;


                }

            }




           price1.getDouble = r+r
    }
}





    public void createAndShowGUI(){
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500,500);
    setLocation(100,100);
    }


    public static  void  main(String args[]){
    Try1 ty = new Try1();
    ty.createAndShowGUI();
    ty.pack();


}

}
最终会像这样:

public void itemStateChanged(ItemEvent e){
     if(e.getStateChange() == ItemEvent.SELECTED){
          double price = priceMap.get(e.getItem());

          //do something with the price
     }
 }
。。。
公共Try1(){
HashMap价格=新的HashMap();
价格。卖出价(“,0.0”);
卖出价(“安格斯堡-P60”,60.0);
//将所有其他项目放入地图中
...
ItemListener jcb=新的ItemHandler(价格);
...
}
私有类ItemHandler实现ItemListener{
私人地图价格;
公共项目处理程序(HashMap价格){
价格=价格;
}
公共无效itemStateChanged(ItemEvent e){
如果(如getStateChange()==ItemEvent.SELECTED){
双倍合计=0.0;
总计+=prices.get(x1.getSelectedItem());
总计+=prices.get(x2.getSelectedItem());
total+=prices.get(x3.getSelectedItem());
总计+=prices.get(x4.getSelectedItem());
总计+=prices.get(x5.getSelectedItem());
价格1.setText(“+总计);
}
}                     
} 

由于您似乎需要更多的提示,以下是装满鳗鱼的气垫船首次提出的想法:

首先定义一个
FoodItem

 ...
 public Try1(){
     HashMap<String , Double> prices = new HashMap<>();
     prices.put("" , 0.0);
     prices.put("Angusburger - P60" , 60.0);
     //put all the other items into the map

     ...
     ItemListener jcb = new ItemHandler(prices);
     ...
 }

 private class ItemHandler implements ItemListener{
      private HashMap<String , Double> prices;

      public ItemHandler(HashMap<String , Double> prices){
           this.prices = prices;
      }

      public void itemStateChanged(ItemEvent e){
           if(e.getStateChange() == ItemEvent.SELECTED){
                 double total = 0.0;

                 total += prices.get(x1.getSelectedItem());
                 total += prices.get(x2.getSelectedItem());
                 total += prices.get(x3.getSelectedItem());
                 total += prices.get(x4.getSelectedItem());
                 total += prices.get(x5.getSelectedItem());

                 price1.setText("" + total);
           }
      }                     
 } 
然后,使用
JComboBox
。我个人对装满鳗鱼的气垫船的建议是使用列表来存储箱子:

public class FoodItem {
    private String name;
    private double cost;

    public FoodItem(String name, double cost) {
        this.name = name;
        this.cost = cost;
    }

    @Override 
    public String toString() {
        return name;
    }

    public getCost() {
        return cost;
    }
}
List box=Arrays.asList(
新JComboBox(新FoodItem[]{new FoodItem(“…”,…)、new FoodItem(“…”,…)、new FoodItem(“…”,…)}),
新JComboBox(新FoodItem[]{new FoodItem(“…”,…)、new FoodItem(“…”,…)、new FoodItem(“…”,…)}),
新JComboBox(新FoodItem[]{new FoodItem(“…”,…)、new FoodItem(“…”,…)、new FoodItem(“…”,…)}),
新JComboBox(新FoodItem[]{new FoodItem(“…”,…)、new FoodItem(“…”,…)、new FoodItem(“…”,…)})
新JComboBox(新FoodItem[]{new FoodItem(“…”,…)、new FoodItem(“…”,…)、new FoodItem(“…”,…)});
//计算总数
双倍合计=0;
对于(JComboBox-box:box)合计+=box.getSelectedItem().getCost();
首先。。。 创建一个POJO,它封装您需要的数据,包括要显示的文本和项的值

List<JComboBox<FoodItem>> boxes = Arrays.asList(
    new JComboBox<>(new FoodItem[] { new FoodItem("...",...),new FoodItem("...",...),new FoodItem("...",...) }),
    new JComboBox<>(new FoodItem[] { new FoodItem("...",...),new FoodItem("...",...),new FoodItem("...",...) }),
    new JComboBox<>(new FoodItem[] { new FoodItem("...",...),new FoodItem("...",...),new FoodItem("...",...) }),
    new JComboBox<>(new FoodItem[] { new FoodItem("...",...),new FoodItem("...",...),new FoodItem("...",...) })
    new JComboBox<>(new FoodItem[] { new FoodItem("...",...),new FoodItem("...",...),new FoodItem("...",...) }));

// compute the total
double total = 0;
for (JComboBox<FoodItem> box : boxes) total += box.getSelectedItem().getCost();
第二 创建一个数组或组合框的
列表

public interface FoodItem {
    public String getText();
    public double getCost();
}
第四。。。 使用
ActionListener
来检测何时发生更改(我会更新
createFoodItemComboBox
方法来自动执行此操作)

private ActionListener ActionHandler=new ActionHandler();
//...
受保护的JComboBox createFoodItemComboBox(FoodItem foodItems){
//...
cb.addActionListener(actionHandler);
返回cb;
}
//...
公共类ActionHandler实现ActionListener{
已执行的公共无效操作(操作事件evt){
双计数=0;
用于(JComboBox cb:foodItems){
FoodItem fi=(FoodItem)cb.getSelectedItem();
如果(fi!=null){
tally+=fi.getCost();
}
}
price1.setText(NumberFormat.getCurrencyInstance().format(tally));
}
}

例如

您的变量名很糟糕,您能帮我吗?就像只获取所需组合框的总和并将其放入price1I的textfield中一样,我会重新执行整个操作。我将创建一个FoodItem类,该类包含项目名称、类型和每项成本,并将使用此类对象的JComboxes。将组合框中的每个项目包装在POJO中,POJO具有一个“display”值和一个与之关联的“numeric”值。然后将所有组合框放置在一个数组中,在其上循环,从每个组合框中获取所选项目,并使用其“数值”值计算sumgree with@HovercraftFullOfEels。除此之外,我会使用组件集合(例如
List
)而不是乘以变量的数量。因此,我将删除所有开关案例,并用它们替换它们?这样会更简单,也更容易修改。您必须创建一个包含所有价格的地图(将空值设置为0,对于未选择的项目也设置为0)。paul,谢谢您的时间,但您能使用我的代码并修改它吗?@我真的不擅长programming@kevin所以你应该成为一个更好的程序员。。。你不可能总是要求别人做你自己的工作事实上,我学的是电子和通讯工程师,数学是我的专业。所以我很难解决这个问题,先生。迪西尔,你能发布一个节目的截图吗?idk“foodItems=newArrayList(5);”是什么意思?这在GUI形式中适用吗?是的,一直都在做这种事情
private List<JComboBox> foodItems;
//...
foodItems = new ArrayList<JComboBox>(5);
foodItems.add(createFoodItemComboBox(
    createFoodItem("Angus Burger", 60), 
    createFoodItem("Australasian Burger", 60),
    createFoodItem("BBQ Burger", 60),
    createFoodItem("Buffalo Burger", 60));
//...

protected JComboBox<FoodItem> createFoodItemComboBox(FoodItem foodItems) {
    DefaultComboBoxModel<FoodItem> model = new DefaultComboBoxModel<>();
    for (FoodItem fi : foodItems) {
        model.addElement(fi);
    }
    JComboBox cb = new JComboBox<FoodItem>(model);
    return cb;
}

protected FoodItem createFoodItem(String text, double price) {
    // You'll have to create your own implementation of FoodItem
    return new DefaultFoodItem(text, price);
}
public static class FoodItemListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value instanceof FoodItem) {
            FoodItem fi = (FoodItem) value;
            setText(fi.getText() + " - " + NumberFormat.getCurrencyInstance().format(fi.getCost()));
        }
        return this;
    }

}
private ActionListener actionHanlder = new ActionHandler();
//...
protected JComboBox<FoodItem> createFoodItemComboBox(FoodItem foodItems) {
    //...
    cb.addActionListener(actionHandler);
    return cb;
}

//...

public class ActionHandler implements ActionListener {
    public void actionPerformed(ActionEvent evt) {
        double tally = 0;
        for (JComboBox<FoodItem> cb : foodItems) {
            FoodItem fi = (FoodItem)cb.getSelectedItem();
            if (fi != null) {
                tally += fi.getCost();
            }
        }
        price1.setText(NumberFormat.getCurrencyInstance().format(tally));
    }
}