jim*_*123 1 java swing jbutton
我正在制作一个tictactoe游戏,其中每个棋盘片由JButton代表.当有人单击该按钮时,文本将更改为"X"或"O".我正在写一个重置功能,它将所有按钮中的文本重置为"".我使用getComponents()方法从数组访问所有按钮.
我只是想知道我做错了什么因为这个位编译正确
component[i].setEnabled(true);
Run Code Online (Sandbox Code Playgroud)
但这一点没有
component[i].setText("");
Run Code Online (Sandbox Code Playgroud)
我收到"找不到符号"错误.请看下面的代码.我只包括我认为必要的代码.
JPanel board = new JPanel(new GridLayout(3, 3));
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
board.add(button1);
board.add(button2);
board.add(button3);
board.add(button4);
board.add(button5);
board.add(button6);
board.add(button7);
board.add(button8);
board.add(button9);
public void reset()
{
Component[] component = board.getComponents();
// Reset user interface
for(int i=0; i<component.length; i++)
{
component[i].setEnabled(true);
component[i].setText("");
}
// Create new board logic
tictactoe = new Board();
// Update status of game
this.updateGame();
}
Run Code Online (Sandbox Code Playgroud)
getComponents ()返回一个Components 数组,它没有setText(String)方法.您应该将JButton实例保留为类成员(这是我强烈建议的方式),并直接使用它们,或循环遍历所有Component对象,检查它是否是JButton实例.如果是,则将其明确地转换为a JButton,然后调用setText(String)它.例如
public void reset()
{
Component[] component = board.getComponents();
// Reset user interface
for(int i=0; i<component.length; i++)
{
if (component[i] instanceof JButton)
{
JButton button = (JButton)component[i];
button.setEnabled(true);
button.setText("");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13251 次 |
| 最近记录: |