我被困在一项任务中,每次用户点击按钮时我都需要更新文本字段.总共有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
}
}
最佳答案 这是因为您将snickers和totalItems声明为actionPerformed方法的本地字段,因此每次单击时都会创建并初始化为0.考虑以下方法之一:
>将这些字段设为类的静态字段
>从当前按钮获取士力架和totalItems,将它们解析为int值并根据这些值进行计算