使用ActionListeners避免全局变量



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

基本上,我希望能够创建一个带有JButton的JFrame,在这个JButton上,会有一个数字。每次按下J按钮,数字都会增加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 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(...);
}
});
}
}

最新更新