亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么對象數組中的元素沒有更新?

為什么對象數組中的元素沒有更新?

慕婉清6462132 2021-12-01 19:56:20
在使用 JavaFX 創建應用程序時,我遇到了一個小問題 - 我的數組中的元素不知何故不會隨著對這些元素所做的更改而更新。一開始我想指出 - 不要關注我的應用程序的結構和模型 - 我已經知道它不好,我改變了它,但我仍然不明白為什么我的問題存在。我的數組的初始化方式如下:public class GameBoardAI implements IGameModel{Random rand = new Random();int currentPlayer = 1;TicTacViewController tacController = new  TicTacViewController();Button[] buttonss = new Button[]{ tacController.btn1, tacController.btn2, tacController.btn3, tacController.btn4,         tacController.btn5, tacController.btn6, tacController.btn7, tacController.btn8, tacController.btn9};  問題是,當我創建按鈕數組時,按鈕還沒有連接到視圖,所以它們仍然是空值。當我試圖在我的按鈕上調用一些方法時,我遇到了一個問題:public void switchPlayer() {if(currentPlayer == 1){                  currentPlayer=2;    buttonss[rand.nextInt(9)].fire();}if(currentPlayer == 2)    currentPlayer = 1;}你可以在這里看到,我試圖從我在實例變量中創建的按鈕數組中獲取一些隨機按鈕。這是代碼的一部分,當按鈕位于 TicTacViewController 中時:    public class TicTacViewController implements Initializable{@FXMLprivate Label lblPlayer;@FXMLprivate Button btnNewGame;@FXMLprivate GridPane gridPane;private static final String TXT_PLAYER = "Player: ";private IGameModel game = new GameBoard();@FXMLpublic Button btn1;@FXMLpublic Button btn2;@FXMLpublic Button btn3;@FXMLpublic Button btn4;@FXMLpublic Button btn5;@FXMLpublic Button btn6;@FXMLpublic Button btn7;@FXMLpublic Button btn8;@FXMLpublic Button btn9;據我了解,問題是,當我將數組創建為實例變量時,mu 按鈕仍然為空 - 它們尚未連接到視圖。但是這里發生了一些奇怪的事情:當我將數組初始化放在 switchPlayer 方法中而不是將其作為實例變量執行時 - 一切正常。所以看起來當我在調用方法時創建數組時按鈕已經連接到視圖并且沒有問題。它破壞了我對引用變量的了解 - 為什么當我們將數組創建為實例變量時它不起作用?因為我認為即使我們在數組中有一個引用變量 - 當我們更改這個引用變量時,它們也會在我們的數組中更改。更具體地說 - 即使當我們初始化一個數組并且按鈕還沒有連接到視圖時,它們也會在之后連接 - 所以當我們調用 switchPlayer 方法時,按鈕應該已經連接到視圖 - 但編譯器告訴我他們是空的。有人可以解釋我這里有什么問題嗎?為什么在調用方法時按鈕仍然為空,因為它們在數組創建中,即使它們之后連接到視圖?
查看完整描述

1 回答

?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

Java 是一種傳值語言。對象類型變量不是對象指針,它們只是保存一個對象引用(即內存地址)。例子:


String str = "Hello"; // A String type variable holding reference of "Hello" string

String str2 = str; // Variable "str2" now copies the reference of "str"

String str2 = "World"; // Variable "str2" changes the reference it holds to the string "World" (in other word, it is being replaced)

它經常被混淆,因為以下是有效的:


List<String> foo = new ArrayList<>(); // Let foo hold the reference of an empty arraylist

List<String> bar = foo; // Let bar hold the reference that is held by foo

bar.add("hello");

System.out.println(foo); // Prints "[hello]"

這是有效的,因為bar已經復制了ArrayListfrom的對象引用foo,因此對ArrayListvia 的任何操作bar都將由 反映foo,因為它們都持有相同的對象引用。


回到你的問題。如果tacController尚未加載 FXML 文件,則所有Button引用都將為null. 所以你要做的是復制null引用并將這些null引用保存在數組中。因此,您將永遠無法訪問實際Button對象。


查看完整回答
反對 回復 2021-12-01
  • 1 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號