我坚持完成一项任务,每次用户点击按钮时我都需要更新文本字段。总共有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
}
}
答案 0 :(得分: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了解详情
答案 1 :(得分:0)
为您的按钮添加动作侦听器
buttonName.addActionListener(this);
另外,编写保存值的变量以显示为全局变量。不要在函数内部声明
试试这段代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawOval implements ActionListener
{
JButton genderBtn = new JButton("gender");
JFrame frm = new JFrame();
JTextField displayTF = new JTextField(15);
int i = 0;
public DrawOval(){
displayTF.setText(""+i);
frm.setTitle("Grocery");
frm.setVisible(true);
frm.setSize(200,100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setResizable(true);
frm.setLayout(new FlowLayout());
frm.add(displayTF);
frm.add(genderBtn);
genderBtn.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == genderBtn){
i++;
displayTF.setText(""+i);
}
}
public static void main(String args[]){
new DrawOval();
}
}
答案 2 :(得分:-1)
这是因为您将snickers
和totalItems
声明为actionPerformed
方法的本地字段,因此每次单击时都会创建并初始化为0。考虑以下方法之一:
snickers
和totalItems
,将它们解析为int值并根据这些值进行计算