我被困在一项任务中,每次用户点击按钮时我都需要更新文本字段。总共有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。考虑以下方法之一:
snickers
和totalItems
,将它们解析为int值并根据这些值进行计算所有“计数器”都是局部变量,因此每次调用qazxsw poi时都会重新初始化它们
你应该改为计数器实例字段......
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
另外,写入保存值的变量作为全局变量显示。不要在函数内部声明
试试这段代码:
buttonName.addActionListener(this);