Nat*_*zan 5 java swing actionlistener textfield
我陷入了一项任务,每次用户单击按钮时我都需要更新文本字段。总共有 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
}
}
Run Code Online (Sandbox Code Playgroud)
Ton*_* Vu -1
这是因为您将snickers和声明totalItems为方法的本地字段actionPerformed,因此每次单击时它们都会被创建并初始化为 0。考虑以下方法之一:
snickers和totalItems,将它们解析为 int 值并根据这些值进行计算| 归档时间: |
|
| 查看次数: |
4617 次 |
| 最近记录: |