[英]Swing - using getComponent() to update all JButtons
我正在做一個單板游戲,其中每個棋子都由一個JButton表示。 當有人單擊按鈕時,文本將更改為“ X”或“ O”。 我正在編寫一個重置功能,該功能將所有按鈕中的文本重置為“”。 我正在使用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<component.length; i++)
{
if (component[i] instanceof JButton)
{
JButton button = (JButton)component[i];
button.setEnabled(true);
button.setText("");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.