java - 单击按钮时增加一个值并使用该值更新文本字段

标签 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 
              }
          }

最佳答案

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

关于java - 单击按钮时增加一个值并使用该值更新文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787190/

相关文章:

java - 在 JPanel 上使用 ImageIcon() 没有显示图像

java - JTable里面的JScrollPane单元格大小和表格大小

java - 在 actionListener 中将 JPanel 添加到 contentPane

java - Java 中的 GUI,监听器的私有(private)类不起作用

java - eclipse中GUI界面异常

java - 在数据库连接中,Class.forName 的作用是什么?

java - Xcode 4.5.1 : Linker Error: NSJavaVirtualMachine, 找不到体系结构 i386 的符号

java - 使用状态机解析 wiki 标记

java - 在java应用程序中使用黑莓相机选择已存档的照片

java - Actionlistener/JComboBox 冲突