gpt4 book ai didi

java - 单击按钮时增加一个值并使用该值更新文本字段

转载 作者:搜寻专家 更新时间:2023-11-01 03:21:26 26 4
gpt4 key购买 nike

我被困在一项作业中,每次用户单击按钮时我都需要更新文本字段。总共有 5 个按钮,每个按钮都有自己的文本字段,单击它们时应更新。我遇到的问题是多次单击时计数器似乎没有更新文本字段。所以我第一次点击按钮时,文本字段会显示“1”,但在多次点击后它仍然如此。

private class ButtonListener implements ActionListener 
{
public void actionPerformed(ActionEvent e)
{
int snickers = 0;
int butterfinger = 0;
int lays = 0;
int coke = 0;
int dietCoke = 0;
int totalItems = 0;
double totalPrice = (totalItems * PRICE);

if (e.getSource() == snickersButton)
{
totalItems++;

snickers++;
quantityTextS.setText(String.valueOf(snickers)); //Display snickers value in text field
itemsSelectedText.setText(String.valueOf(totalItems)); //Display total items value in text field

if(snickers > MAX)
{
JOptionPane.showMessageDialog(null, "The maximum number of each item that can be selected is 3.",
"Invalid Order Quantity", JOptionPane.ERROR_MESSAGE);
quantityTextS.setText("3"); //Set text to 3
}
}

最佳答案

你所有的“计数器”都是局部变量,因此每次调用 actionPerformed 时它们都会被重新初始化

您应该改为创建计数器实例字段...

private class ButtonListener implements ActionListener 
{
private int snickers = 0;
private int butterfinger = 0;
private int lays = 0;
private int coke = 0;
private int dietCoke = 0;
private int totalItems = 0;
public void actionPerformed(ActionEvent e)
{
double totalPrice = (totalItems * PRICE);

if (e.getSource() == snickersButton)
{

不过,这假定您对所有按钮使用相同的 ButtonListener 实例

看看Understanding Class Members了解更多详情

关于java - 单击按钮时增加一个值并使用该值更新文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787190/

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