使用 ActionListeners 避免全局变量

Avoiding Global Variables with ActionListeners

所以我正在做一个 GUI 项目,运行 遇到了一个小问题。我已经对全局变量感到太舒服了,所以我决定练习在没有全局变量的情况下工作。这是我设计的一个简单的小项目。

基本上,我希望能够创建一个带有 JButton 的 JFrame,并且在这个 JButton 上会有一个数字。每次按下 JButton,数字都会增加 1。很简单,对吧?好吧,我意识到没有全局变量,我不知道该怎么做。这是删除了不必要位的代码。

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JFrame;
import javax.swing.JButton;

public class SOQ
{

   public SOQ()
   {

      JFrame frame = new JFrame("SOQ");
      JButton button = new JButton("PRESS HERE");

      programLoop(frame, button);

   }

   public JFrame buildFrame(JFrame frame)
   {

          //unnecessary to include

      return frame;

   }

   public void programLoop(JFrame frame, JButton button)
   {

      int iteration = 1;

      frame = buildFrame(frame);
          //unnecessary to include


      button.addActionListener(
             new ActionListener()
             {

                public void actionPerformed(ActionEvent event)
                {

                   //iteration++; //this line returns an error saying the var should be final

                   if(iteration >= 5)
                   {

                      //this is what I want it to reach

                   }

                }

             }

             );

      frame.add(button);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);

   }

   public static void main(String[] args)
   {

      SOQ mbpps = new SOQ();

   }

}

现在,查看代码,您会发现我犯了一个大错,您不能更改 ActionListener 中的值。所以我尝试了几种不同的方法。我试图用一种方法代替 iteration++,该方法本质上会将变量作为参数,但事实证明这是不可能的,因为新方法无法触及 iteration,因为 iteration 对于不同的方法是局部的,而不是全局的。我什至尝试弄乱 ActionListener 并可能在另一个 class 中实现它,或者在接口中扩展它,但这些都没有解决。这是我必须使用全局变量的情况吗?因为我看不到任何其他方法。

这里有几个想法,来自我的脑海:

class MyRandomClass {
    int thisIsNotAGlobal;  //It's an instance variable.
    ...
    void someFoobarMethod(...) {
        JButton button = ...;
        Thingy someThingy = ...;

        button.addActionListener(
             new ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                    thisIsNotAGlobal++;
                    someThingy.methodWithSideEffects(...);
                }
             });
    }
}