问题描述
我正在制作一个tictactoe游戏,其中每个棋盘片由JButton代表。当有人单击该按钮时,文本将更改为X或O。我正在写一个重置功能,它将所有按钮中的文本重置为。我正在使用getComponents()方法从数组中访问所有按钮。
I am making a tictactoe game where each board piece is represented by a JButton. When someone clicks the button the text is changed to "X" or "O". I am writing a reset function which resets the text in all the buttons to "". I am accessing all the buttons from an array using getComponents() method.
我只是想知道我做错了什么因为这个位编译正确
I just wondered what I am doing wrong because this bit compiles correctly
component[i].setEnabled(true);
但这一位不是
component[i].setText("");
我收到无法找到符号错误。请看下面的代码。我只包含了我认为必要的代码。
I get a "cannot find symbol" error. Please have a look at the code below. I only included the code I thought was necessary.
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();
}
推荐答案
getComponents()
返回一个 Component
的数组,它没有 setText(String)
方法。您应该将 JButton
实例保留为类成员(这是我强烈建议的方式),并直接使用它们,或循环遍历所有组件
对象,检查它是否是 JButton
实例。如果是,则显式地将其转换为 JButton
,然后在其上调用 setText(String)
。例如,
getComponents ()
returns an array of Component
s, which does not have a setText(String)
method. You should either keep your JButton
instances as class members (this is the way I strongly suggest), and use them directly, or loop through all the Component
objects, check if it is a JButton
instance. If it is, explicitly cast it as a JButton
, then call setText(String)
on it. E.g.
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("");
}
}
}
这篇关于Swing - 使用getComponent()更新所有JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!