使用ItemEvent从JComboBox计算总成本

时间:2016-03-23 01:35:53

标签: java swing jcombobox

我有两个JComboBox个组件和一个JLabel。两个组合框都包含字符串,标签应该添加价格。我的问题是我无法弄清楚如何将int值设置为组合框选择,然后添加这些整数并在标签上输出它们。到目前为止,它坚持0并且没有变化。

欢迎所有代码更正/建设性批评。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.*;

public class CottageRental extends JFrame implements ItemListener {

    // Declare all instance data  (primitives and objects used) 
    private int WIDTH = 675;
    private int HEIGHT = 320; 
    Container con; 
    JButton [] button; 
    JLabel label1, label2, label3;
    JComboBox box1, box2;
    String[] box1options = {"1 Bedroom - $600", "2 Bedroom - $800", "3 Bedrooms - $1,000"};
    String[] box2options = {"Horse Back Riding - $60", "Rafting - $40", "Row  Boat Rental - $50"};
    int[] box1prices = {600, 800, 1000};
    int[] box2prices = {60, 40, 50};
    private Font font1 = new Font("Arial", Font.BOLD, 30);
    public int total1, total2;
    //constructor 
    public CottageRental() {
        super("Cottage Rental"); 
        con = getContentPane(); 
        con.setBackground(Color.GRAY);
        con.setLayout(new BorderLayout()); 
        setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

        //instantiate all the components in the constructor 

    }

    public void createGUI() {
        label1 = new JLabel("WoodBerry Cottage Rental");
        label1.setFont(font1);
        label1.setBackground(Color.WHITE);
        label2 = new JLabel("Rental Amount Due: " + total1 + " and " + total2);
        box1 = new JComboBox(box1options);
        box2 = new JComboBox(box2options);
        con.add(label1, BorderLayout.NORTH);
        con.add(label2, BorderLayout.SOUTH);
        con.add(box1, BorderLayout.WEST);
        con.add(box2, BorderLayout.EAST);
        box1.addItemListener(this);
        box2.addItemListener(this);

    }


    public static void main(String[] args) {
        CottageRental   object  = new CottageRental(); 
        object.createGUI(); 
    }


    @Override
    public void itemStateChanged(ItemEvent e) {
        Object source = e.getSource();
        if(e.getStateChange()==ItemEvent.SELECTED) {  
            if (source == box1) {
                int choice1 = box1.getSelectedIndex();
                if (choice1 == 0) {
                    total1 = box1prices[0];
                } else if (choice1 == 1) {
                    total1 = box1prices[1];
                } else if (choice1 == 2) {
                    total1 = box1prices[2];
                }
            }
            if (source == box2) {
                int choice2 = box2.getSelectedIndex();
                if (choice2 == 0) {
                    total2 = box2prices[0];
                } else if (choice2 == 1) {
                    total2 = box2prices[1];
                } else if (choice2 == 2) {
                    total2 = box2prices[2];
                }
            }
        }  
    }
}

2 个答案:

答案 0 :(得分:1)

您可以压缩public void itemStateChanged(ItemEvent e)方法,因为您已经知道所选索引与价格数组中的索引相同。您已经通过使这些价格数组与JComboBox的大小匹配来间接分配int值。此外,标签不会更改,因为您不更新标签上的文字。

public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if(e.getStateChange()==ItemEvent.SELECTED) {
        if(source.equals(box1) || source.equals(box2) {
            total1 = box1prices[box1.getSelectedIndex()];
            total2 = box2prices[box2.getSelectedIndex()];
            label2.setText("Rental Amount Due: " + total1 + " and " + total2);
        }
    }
}

答案 1 :(得分:1)

首先制作一个POJO(普通旧Java对象),它分别带有描述和价格。

public class Product {
    private String description;
    private double price;

    public Product(String description, double price) {
        this.description = description;
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return getDescription() + " - " + NumberFormat.getCurrencyInstance().format(getPrice());
    }
}

现在,使用它来构建您的选项......

private Product[] box1options = {
    new Product("1 Bedroom", 600), 
    new Product("2 Bedroom", 800),
    new Product("3 Bedroomsm", 1_000)};
private Product[] box2options = {
    new Product("Horse Back Riding", 60), 
    new Product("Rafting", 40), 
    new Product("Row  Boat Rental", 50)};
private JComboBox<Product> box1Prices = new JComboBox<Product>(box1options);
private JComboBox<Product> box2Prices = new JComboBox<Product>(box2options);

然后更新你的听众......

ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        updateTally();
    }
};

box1Prices.addActionListener(listener);
box2Prices.addActionListener(listener);

最后更新计数器的逻辑......

protected void updateTally() {
    Product p1 = (Product) box1Prices.getSelectedItem();
    Product p2 = (Product) box2Prices.getSelectedItem();

    double price1 = p1 != null ? p1.getPrice() : 0d;
    double price2 = p2 != null ? p2.getPrice() : 0d;

    tallyLabel.setText(NumberFormat.getCurrencyInstance().format(price1 + price2));
}

这样,您可以在单个工作单元中包含描述的价格,从而更容易更改价格(或描述)而无需更改其余代码