如何解决如何动态更改 JComboBox 中的项目数
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。 mti2935
解决方法
作为一个想法......与其进行所有这些从整数到字符串和字符串到整数的转换以填充您的组合框,为什么不只使用一个整数组合框?无论如何,您最初都是在处理整数数量值:
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 组件而不是组合框。在我看来,这个用例中的下拉列表总是有点突兀。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。