Swing – 使用getComponent()更新所有JButton
我正在制作一个tictactoe游戏,其中每个棋盘都由JButton代表。 当有人单击该按钮时,文本将更改为“X”或“O”。 我正在写一个重置function,它将所有按钮中的文本重置为“”。 我使用getComponents()方法访问数组中的所有按钮。
我只是想知道我做错了什么,因为这个位编译正确
component[i].setEnabled(true);
但这一点没有
component[i].setText("");
我收到“找不到符号”错误。 请看下面的代码。 我只包括我认为必要的代码。
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
实例保留为类成员(这是我强烈建议的方式),并直接使用它们,或循环遍历所有Component
对象,检查它是否是JButton
实例。 如果是,则显式地将其转换为JButton
,然后在其上调用setText(String)
。 例如
public void reset() { Component[] component = board.getComponents(); // Reset user interface for(int i=0; i