单击按钮时增加值,并使用该值更新文本字段

问题描述 投票:4回答:3

我被困在一项任务中,每次用户点击按钮时我都需要更新文本字段。总共有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 
              }
          }
java swing actionlistener textfield
3个回答
-1
投票

这是因为你将snickerstotalItems声明为actionPerformed方法的局部字段,因此每次单击时它们都会被创建并初始化为0。考虑以下方法之一:

  1. 使这些字段成为类的静态字段
  2. 从当前按钮获取snickerstotalItems,将它们解析为int值并根据这些值进行计算

3
投票

所有“计数器”都是局部变量,因此每次调用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了解更多详情


0
投票

向您的按钮添加动作侦听器

Understanding Class Members

另外,写入保存值的变量作为全局变量显示。不要在函数内部声明

试试这段代码:

buttonName.addActionListener(this);
© www.soinside.com 2019 - 2024. All rights reserved.