gpt4 book ai didi

java - isSelected() 不识别 JRadioButton 和 JCheckBox 被选中

转载 作者:行者123 更新时间:2023-11-29 06:00:08 25 4
gpt4 key购买 nike

我是新来的,这是我的第一篇文章。

我有一个非常具体的需求,需要编写这个非常简单的应用程序,仅调用 isSelected() 方法来检查是否已选择 JRadioButton 或 JCheckBox。这意味着我不想遍历 ButtonGroup 并调用它的 getSelection() 方法。

我的代码也与托尼·加迪斯 (Tony Gaddis) 撰写的教科书中的代码相同,我目前正在学习这本书:Starting Out With JavaFrom Control Structures through Objects . 第 4 版

这是一个逻辑问题,因为应用程序编译和运行没有错误。

这是发生了什么:

我有四个类:BagelsPanel、CoffeePanel、ToppingsPanel 和 GUI 类 BagelApp - 所有这些类都扩展了 JPanel,除了 BagelApp 类扩展了 JFrame。

该应用的用途是让用户选择咖啡、百吉饼和配料,并返回所有选择的总价。问题是它一直返回 $0.00。

我怀疑,出于某种原因,isSelected() 无法识别已选择的内容。

我将涉及这些问题的 BagelsPanel 和 GUI 类代码贴在下面:

public double calcBagel() {

double total = 0.00;

if(button1.isSelected())
total = PLAIN;
else if(button2.isSelected())
total = WHOLE_WHEAT;
else if(button3.isSelected())
total = CINNA_RAISON;
else if(button4.isSelected())
total = EVERYTHING;

return total;
}

上面是 BagelsPanel 类中的 calcBagel() 方法,它调用 isSelected() 方法来检查选择了哪个 JRadioButton,然后分配它的价格到 total。下面是 GUI 类:

public void buildPanel() {

panel = new JPanel();
calc = new JButton("Calculate");
calc.addActionListener(new ButtonListener());
panel.add(calc);
}
private class ButtonListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

double subtotal = 0.0;
double total = 0.0;
bagels = new BagelPanel();
coffee = new CoffeePanel();
toppings = new ToppingsPanel();

subtotal = bagels.calcBagel() + coffee.calcCoffee() +
toppings.calcToppings();
double tax = subtotal * TAX;
total = subtotal + tax;

DecimalFormat dollar = new DecimalFormat("$0.00");

JOptionPane.showMessageDialog(null, "Your total is: "
+ dollar.format(total));
}
}

这里有一些见解:如果我将 BagelsPanel 类中的 calcBagel() 方法中的 double 变量 total 更改为 1.0,然后运行应用程序并单击 JRadioButton“计算”,它会准确地支持 JOptionPane 告诉我我的总额是 1.06 美元(最终双变量 TAX 设置为 0.06)。

如果能得到任何帮助,我将不胜感激。我还是 Java 的初学者,不太明白为什么我的逻辑不正确。我很尴尬这可能是非常微不足道的,但我已经检查了这本书并且代码是相同的。有什么建议吗?

最佳答案

您的问题就在这里,在您的actionPerformed 方法中:

    double total = 0.0;
bagels = new BagelPanel();
coffee = new CoffeePanel();
toppings = new ToppingsPanel();

您不是在显示的面板上调用方法 calcBagel()、calcCoffee()、calcToppings(),而是凭空创建新面板并在其上调用“calc-methods” .当然,它们是用户在 UI 中操作的对象的不同对象。您应该保留对最初添加到 GUI 的面板的引用,并在这些面板上调用“计算方法”,而不是在新创建的对象上。

P.S:您的代码确实混合了模型和 View 。

关于java - isSelected() 不识别 JRadioButton 和 JCheckBox 被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10467414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com