【问题标题】:How can I dynamically change the number of items in a JComboBox如何动态更改 JComboBox 中的项目数
【发布时间】:2021-06-24 13:45:24
【问题描述】:
private void dropDownMenu(JPanel jp1, String prodId){
    int len = storeManager.getInv().getStockAmount(prodId);
    int[] nums = new int[len];
    String[] numPossible = new String[len];

    for (int i=0; i<len; i++){
        nums[i] = i+1;
    }
    for (int i=0; i<len; i++){
        numPossible[i] = String.valueOf(nums[i]);
    }
    JComboBox<String> cb = new JComboBox<String>(numPossible);
    JButton okButton = new JButton("Add To Cart");
    okButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Product p1 = storeManager.getInv().getProd(prodId);
            String quan = (String) cb.getSelectedItem();
            int quantity = Integer.parseInt(quan);
            if (quantity > storeManager.getInv().getStockAmount(prodId)) {
                System.out.println("Not Enough Stock.");
            } else {
                storeManager.getCart().addToCart(p1, quantity);
                storeManager.getInv().removeStockAmount(prodId, quantity);
                //update the dropdown menu here
            }
        }
    });
    jp1.add(cb);
    jp1.add(okButton);
}

基本上我要寻找的是,每当我从下拉菜单中选择一个数字时,我希望菜单中的项目数量减少添加到购物车的数量。例如,如果我将 5 添加到购物车,那么我希望下拉菜单从允许我选择 10 到 5。 Image of GUI

【问题讨论】:

  • 使用JComboBox removeAllItems 方法删除所有数字,然后添加新的数字集,就像添加原始数字集一样。

标签: java swing user-interface jframe jcombobox


【解决方案1】:

作为一个想法...与其进行所有这些从整数到字符串和从字符串到返回整数的转换来填充您的组合框,为什么不只拥有一个整数组合框呢?无论如何,您最初都是在处理整数值:

JComboBox<Integer> cb = new JComboBox<>();
int len = storeManager.getInv().getStockAmount(prodId);
for (int i = 1; i <= len; i++) {
   cb.addItem(i);
}
cb.setSelectedIndex(0); 

您的动作监听器现在可能看起来像这样:

okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Product p1 = storeManager.getInv().getProd(prodId);
        int quantity = (int) cb.getSelectedItem();
        /* This 'if' statement below would be moot if the Combo-Box 
           is properly updated unless editing is allowed in the combo
           which in this case...disable that feature.     */
        if (quantity > storeManager.getInv().getStockAmount(prodId)) {
            System.out.println("Not Enough Stock.");
        } else {
            storeManager.getCart().addToCart(p1, quantity);
            len = storeManager.getInv().removeStockAmount(prodId, quantity);
            cb.removeAllItems();
            for (int i = 1; i <= len; i++) { cb.addItem(i); }
            cb.setSelectedIndex(0); 
        }
    }
});

使用 JSpinner 组件而不是组合框可能更好。在我看来,这个用例中的下拉列表总是显得有点突兀。

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多