将外部的整数变量添加到动作监听器中。

huangapple go评论68阅读模式
英文:

Adding an outside int into an action listener

问题

这是代码部分的翻译:

public void FensterAufbauen() {
    int i = 0;
    myPanel.setLayout(null);
    myButton.setText("");
    myButton.setBounds(40,70,80,80);
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            if (i % 2 == 0){
                myButton.setText("X");
            }
            else {
                myButton.setText("O");
            }
            i++;
        }
    });
}

如何将 int i 添加到动作监听器中呢?
(由于我在所有的 9 个按钮上都有这个操作,所以不能仅在监听器内部定义 i)?
对不起,提前为可能出现的不清晰之处道歉 - 我对 Java 还比较新。

英文:

I have to do a very small project for school: making a game of tic tac toe in Java using JButtons and I have a short question.

Here's the code:

public void FensterAufbauen() {
    int i = 0;	
	myPanel.setLayout(null);
	myButton.setText("");
	myButton.setBounds(40,70,80,80);
	myButton.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent arg0) {
			if (i % 2 == 0){
			myButton.setText("X");
			}
			else {
			myButton.setText("O");
			}
			i++;
		}
	});
}

Now how would I add the int i into the action listener
(I have this for all 9 buttons so I can't just define i inside the listener)?
I am sorry in advance if anything here seems sloppy - I'm pretty new to Java

答案1

得分: 1

i必须是final的,如果你想从匿名内部类中访问它:

final int i = 0;

当然,这意味着你将无法再对它进行更改。因此,相反地,你可以将i声明为外部类中的非final私有变量,而不是局部变量。或者你也可以将i声明为ActionListener内部的私有变量,在actionPerformed() 函数的正上方。

英文:

i has to be final if you want to access it from within an anonymous inline class:

final int i = 0;

That, of course, will mean you can no longer change it. Thus, instead, declare i as a non-final, private variable in the surrounding class, rather than a local variable. Or you could also declare i as a private variable inside your ActionListener, just above the actionPerformed() function.

huangapple
  • 本文由 发表于 2020年5月29日 05:02:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/62074481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定