Basically, it's giving me a problem about declaring each button in the "for" loop as final before it'll add the text. When I do that, it gives me a ton of other errors. Could somebody help me out with this?
基本上,它给了我一个问题,关于在“for”循环中在添加文本之前声明每个按钮为final。当我这么做的时候,它会给我带来很多其他的错误。有人能帮我一下吗?
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class tictactoe {
public static final int FRAME_WIDTH = 700;
public static final int FRAME_HEIGHT = 200;
public static void main(String[] args)
{
int slots = 9;
JButton[] gameButton = new JButton[9];
JPanel ticTacToeBoard = new JPanel();
ticTacToeBoard.setLayout(new GridLayout(3, 3));
for (int i = 0; i < slots; i++)
{
gameButton[i] = new JButton();
ticTacToeBoard.add(gameButton[i]);
gameButton[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gameButton[i].setText("x");
}
});
}
JButton clearButtons = new JButton("New Game");
JButton exit = new JButton("Exit");
JPanel rightPanel = new JPanel();
JLabel wonLabel = new JLabel();
rightPanel.setLayout(new GridLayout(1, 3));
rightPanel.add(wonLabel);
rightPanel.add(clearButtons);
rightPanel.add(exit);
JFrame mainFrame = new JFrame();
mainFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(1,2));
mainFrame.add(ticTacToeBoard);
mainFrame.add(rightPanel);
}
}
2 个解决方案
#1
5
Try replacing the action listener with this:
试着用以下语句替换动作监听器:
gameButton[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
((JButton)e.getSource()).setText("x");
}
Regarding the original error:
关于原来的错误:
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
在内部类中使用但未声明的任何局部变量、正式方法参数或异常处理程序参数必须被声明为final。任何局部变量,而不是使用一个内部类中声明之前,必须明确分配(§16)身体的内部类。
#2
0
Simply add :
简单的添加:
String buttonText = "Click Me";
jButton.setText(buttonText);
#1
5
Try replacing the action listener with this:
试着用以下语句替换动作监听器:
gameButton[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
((JButton)e.getSource()).setText("x");
}
Regarding the original error:
关于原来的错误:
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.
在内部类中使用但未声明的任何局部变量、正式方法参数或异常处理程序参数必须被声明为final。任何局部变量,而不是使用一个内部类中声明之前,必须明确分配(§16)身体的内部类。
#2
0
Simply add :
简单的添加:
String buttonText = "Click Me";
jButton.setText(buttonText);